// Guided Profile-Creation Wizard — 2-step modal
// Step 1: Name + Zielgruppenbeschreibung (klartext)
// Step 2: Optional Seed-Parameter (Branche, Region, Größe, Notizen) ODER Cold-Start

function NewProfileWizard({ open, onClose, onCreate }) {
  useLang();
  const [step, setStep] = useState(1);
  const [name, setName] = useState('');
  const [audience, setAudience] = useState('');
  const [industry, setIndustry] = useState('');
  const [region, setRegion] = useState('');
  const [companySize, setCompanySize] = useState('');
  const [notes, setNotes] = useState('');
  const [coldStart, setColdStart] = useState(false);

  useEffect(() => {
    if (open) {
      setStep(1);
      setName(''); setAudience('');
      setIndustry(''); setRegion(''); setCompanySize(''); setNotes('');
      setColdStart(false);
    }
  }, [open]);

  if (!open) return null;

  const canAdvance = name.trim().length > 1 && audience.trim().length > 4;
  const initial = (name.trim()[0] || '?').toUpperCase();

  // Build the summary query string that shows up as profile.query
  const buildQuery = () => {
    if (coldStart) return audience.trim().slice(0, 80);
    const parts = [industry, region, companySize].map(s => s.trim()).filter(Boolean);
    return parts.length ? parts.join(' · ') : audience.trim().slice(0, 80);
  };

  const finish = () => {
    const profile = {
      id: 'p_' + Math.random().toString(36).slice(2, 8),
      name: name.trim(),
      short: name.trim().split(/\s+/).slice(0, 3).join(' '),
      initial,
      query: buildQuery(),
      createdAt: new Date().toLocaleDateString(LangStore.get() === 'de' ? 'de-DE' : 'en-US', { day: 'numeric', month: 'long', year: 'numeric' }),
      feedbackCount: 0,
      acceptedCount: 0,
      rejectedCount: 0,
      matchRateStart: 0,
      matchRateNow: 0,
      matchHistory: [0],
      feedbackHistory: [0],
      memory: [],
      reasons: [],
      leads: [],
      seed: coldStart ? null : { industry, region, companySize, notes },
      audience,
    };
    onCreate(profile);
  };

  const Footer = () => (
    <div className="flex-shrink-0 px-8 py-4 bg-white border-t border-line flex items-center justify-between">
      <button onClick={onClose} className="text-[13px] text-ink-muted hover:text-ink">{t('np.abort')}</button>
      <div className="flex items-center gap-2">
        {step === 2 && (
          <Button variant="ghost" onClick={() => setStep(1)}>
            <Icon.ArrowL size={14}/> {t('np.back')}
          </Button>
        )}
        {step === 1 ? (
          <Button variant="brand" onClick={() => canAdvance && setStep(2)} disabled={!canAdvance}>
            {t('np.continue')}
          </Button>
        ) : (
          <Button variant="brand" onClick={finish}>{t('np.create')}</Button>
        )}
      </div>
    </div>
  );

  return (
    <div className="fixed inset-0 z-50 bg-white fade-in flex flex-col" onClick={onClose}>
      <div className="absolute inset-0 pointer-events-none"
           style={{background:'radial-gradient(1200px 600px at 50% -10%, #EEF2FE 0%, transparent 60%)'}}/>
      <div onClick={(e) => e.stopPropagation()} className="relative flex flex-col h-full">
        {/* Top bar */}
        <div className="flex-shrink-0 px-8 py-4 border-b border-line flex items-center justify-between bg-white/80 backdrop-blur-sm">
          <div className="flex items-center gap-3">
            <div className="w-7 h-7 rounded-md bg-ink text-white flex items-center justify-center flex-shrink-0">
              <Icon.Plus size={14}/>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('np.stepOf', { n: step })}</div>
              <div className="text-[14px] font-semibold text-ink leading-tight">{t('np.title')}</div>
            </div>
          </div>
          <button onClick={onClose} className="inline-flex items-center gap-1.5 h-[32px] px-3 rounded-md text-[12.5px] text-ink-muted hover:bg-gray-100 hover:text-ink transition-colors">
            <Icon.X size={14}/> {t('dash.close')}
          </button>
        </div>

        {/* Progress */}
        <div className="flex-shrink-0 px-8 pt-4">
          <div className="max-w-[640px] mx-auto flex gap-1.5">
            <div className={`h-1 flex-1 rounded-full transition-colors ${step >= 1 ? 'bg-[#3465E3]' : 'bg-[#E6ECF5]'}`}/>
            <div className={`h-1 flex-1 rounded-full transition-colors ${step >= 2 ? 'bg-[#3465E3]' : 'bg-[#E6ECF5]'}`}/>
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto">
          <div className="max-w-[640px] mx-auto px-8 py-8">
            {/* ---------- STEP 1 ---------- */}
            {step === 1 && (
              <div className="space-y-4 fade-in">
                <div>
                  <h2 className="text-[22px] font-semibold text-ink tracking-tight">{t('np.step1Title')}</h2>
                  <p className="text-[13.5px] text-ink-muted mt-1.5 leading-[1.55]">{t('np.step1Sub')}</p>
                </div>

                <div className="flex gap-3 items-start pt-2">
                  <div className="w-11 h-11 rounded-md bg-[#3465E3] text-white flex items-center justify-center text-[18px] font-semibold flex-shrink-0">{initial}</div>
                  <div className="flex-1">
                    <label className="block text-[12px] font-medium text-ink mb-1.5">{t('np.name')}</label>
                    <input
                      autoFocus value={name} onChange={e => setName(e.target.value)}
                      placeholder={t('np.nameP')}
                      className="w-full border border-line rounded-md px-3 py-2 text-[14px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]"/>
                  </div>
                </div>

                <div>
                  <label className="block text-[12px] font-medium text-ink mb-1.5">{t('np.audience')}</label>
                  <textarea
                    rows={5} value={audience} onChange={e => setAudience(e.target.value)}
                    placeholder={t('np.audienceP')}
                    className="w-full border border-line rounded-md px-3 py-2.5 text-[14px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3] resize-none leading-[1.55]"/>
                  <p className="text-[11.5px] text-ink-soft mt-1.5 leading-snug">{t('np.audienceHint')}</p>
                </div>
              </div>
            )}

            {/* ---------- STEP 2 ---------- */}
            {step === 2 && (
              <div className="fade-in">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <h2 className="text-[22px] font-semibold text-ink tracking-tight">{t('np.step2Title')}</h2>
                    <p className="text-[13.5px] text-ink-muted mt-1.5 leading-[1.55]">{t('np.step2Sub')}</p>
                  </div>
                  <span className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium mt-1.5 flex-shrink-0">{t('np.optional')}</span>
                </div>

                {/* Cold-start toggle */}
                <label className={`mt-5 flex items-start gap-3 p-3.5 rounded-md border cursor-pointer transition-colors ${
                  coldStart ? 'border-[#3465E3] bg-[#F5F8FE]' : 'border-line hover:bg-gray-50'
                }`}>
                  <input
                    type="checkbox" checked={coldStart} onChange={e => setColdStart(e.target.checked)}
                    className="mt-0.5 accent-[#3465E3] flex-shrink-0"/>
                  <div className="flex-1">
                    <div className="text-[13.5px] font-medium text-ink">{t('np.coldStart')}</div>
                    <div className="text-[12px] text-ink-muted leading-[1.55] mt-0.5">{t('np.coldStartDesc')}</div>
                  </div>
                </label>

                {!coldStart && (
                  <div className="mt-4 grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[12px] text-ink-muted mb-1.5">{t('np.industry')}</label>
                      <input value={industry} onChange={e => setIndustry(e.target.value)} placeholder={t('np.industryP')}
                        className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]"/>
                    </div>
                    <div>
                      <label className="block text-[12px] text-ink-muted mb-1.5">{t('np.region')}</label>
                      <input value={region} onChange={e => setRegion(e.target.value)} placeholder={t('np.regionP')}
                        className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]"/>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-[12px] text-ink-muted mb-1.5">{t('np.companySize')}</label>
                      <input value={companySize} onChange={e => setCompanySize(e.target.value)} placeholder={t('np.companySizeP')}
                        className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]"/>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-[12px] text-ink-muted mb-1.5">{t('np.notes')}</label>
                      <textarea rows={2} value={notes} onChange={e => setNotes(e.target.value)} placeholder={t('np.notesP')}
                        className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3] resize-none"/>
                    </div>
                  </div>
                )}

                {/* Summary card */}
                <div className="mt-5 p-3.5 rounded-md bg-[#F4F7FD] border border-line">
                  <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft">
                    <Icon.Brain size={12}/> {t('np.summaryTitle')}
                  </div>
                  <div className="mt-2 flex items-start gap-2.5">
                    <div className="w-7 h-7 rounded bg-[#3465E3] text-white flex items-center justify-center text-[12px] font-semibold flex-shrink-0">{initial}</div>
                    <div className="min-w-0 flex-1">
                      <div className="text-[13.5px] font-medium text-ink truncate">{name.trim() || '—'}</div>
                      <div className="text-[12px] text-ink-muted leading-[1.5] mt-0.5">
                        {coldStart ? t('np.nothingYet') : (buildQuery() || t('np.nothingYet'))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        <Footer/>
      </div>
    </div>
  );
}

Object.assign(window, { NewProfileWizard });
