/* Mandera Portal — Welcome + dynamic Onboarding (renders from MData.schema()). */

function Chip({ active, onClick, children }) {
  return (
    <button type="button" onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 'var(--radius-pill)',
      cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
      background: active ? 'var(--accent-soft)' : 'var(--surface-sunken)',
      border: '1px solid', borderColor: active ? 'var(--border-accent)' : 'var(--border-default)',
      color: active ? 'var(--accent-text)' : 'var(--text-secondary)', transition: 'all var(--dur-fast) var(--ease-out)',
    }}>
      {active && <window.PIcon n="check" s={14} color="var(--accent-text)" stroke={2.4} />}
      {children}
    </button>
  );
}

function Field({ label, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      <label style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--text-secondary)' }}>{label}</label>
      {children}
      {hint && <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12.5, color: 'var(--text-faint)' }}>{hint}</span>}
    </div>
  );
}

function Welcome({ go }) {
  const acc = window.MAuth.current();
  const client = acc && acc.clientId ? window.MData.client(acc.clientId) : null;
  const brand = (client && client.brand) || 'there';
  const first = brand.split(' ')[0];
  return (
    <div style={{ position: 'relative', minHeight: '100vh', overflow: 'hidden', background: 'var(--bg-canvas)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
      <div style={{ position: 'absolute', inset: 0, background: 'var(--grad-hero)' }} />
      <window.MarkWash opacity={0.22} size={820} pos={{ top: '50%', left: '50%', transform: 'translate(-50%,-50%)' }} />
      <div style={{ position: 'relative', maxWidth: 640, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 26 }}>
        <window.PLogo height={24} />
        <span className="mandera-eyebrow" style={{ marginTop: 18 }}>Welcome aboard · {brand}</span>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 68, lineHeight: 1.1, letterSpacing: '-0.015em', color: 'var(--text-strong)', margin: 0, whiteSpace: 'nowrap' }}>
          Welcome,<br /><span style={{ fontStyle: 'italic', color: 'var(--accent-text)' }}>{first}</span>.
        </h1>
        <p style={{ fontFamily: 'var(--font-sans)', fontSize: 18, lineHeight: 1.6, color: 'var(--text-secondary)', maxWidth: 480, margin: 0 }}>
          We’re thrilled to be working together. Before your dashboard opens, tell us a little about your brand so we can hit the ground running.
        </p>
        <div style={{ display: 'flex', gap: 28, margin: '14px 0 6px' }}>
          {[['clipboard-list', 'Complete onboarding'], ['calendar-check', 'See your schedule'], ['sparkles', 'Watch the work roll in']].map(([ic, t]) => (
            <div key={t} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, width: 130 }}>
              <span style={{ width: 48, height: 48, borderRadius: 'var(--radius-md)', background: 'var(--accent-soft)', border: '1px solid var(--border-accent)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                <window.PIcon n={ic} s={22} color="var(--accent-text)" stroke={1.6} />
              </span>
              <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.4 }}>{t}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 14, marginTop: 8 }}>
          {(() => { const { Button } = window.ManderaDesignSystem_8327ce; return (
            <Button variant="primary" size="lg" iconRight={<window.PIcon n="arrow-right" s={18} color="var(--ink-950)" />} onClick={() => go('onboarding')}>Begin onboarding</Button>
          ); })()}
        </div>
        <p style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text-faint)', margin: 0 }}>This takes about 3 minutes. You can’t reach your dashboard until it’s done.</p>
      </div>
    </div>
  );
}

function Onboarding({ go }) {
  const { Button, Input, Checkbox } = window.ManderaDesignSystem_8327ce;
  const acc = window.MAuth.current();
  const clientId = acc && acc.clientId;
  const schema = window.MData.schema();
  const existing = clientId ? window.MData.onboardingOf(clientId) : { data: {} };

  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [f, setF] = React.useState(() => ({ ...existing.data }));
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const toggle = (k, v, single) => setF((p) => {
    if (single) return { ...p, [k]: v };
    const arr = Array.isArray(p[k]) ? p[k] : [];
    return { ...p, [k]: arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v] };
  });

  const total = schema.length + 1; // +review
  const isReview = step === schema.length;
  const pct = Math.round(((step + 1) / total) * 100);
  const [consent, setConsent] = React.useState(false);

  const submit = () => {
    if (clientId) window.MData.saveOnboarding(clientId, f, 'submitted');
    if (clientId) { const cl = window.MData.client(clientId); window.MData.notify({ audience: 'team', type: 'onboarding', text: (cl ? cl.brand : 'A client') + ' submitted their onboarding brief', link: 'onboarding', refId: clientId }); }
    if (window.MAuth) window.MAuth.markOnboarded();
    setDone(true);
  };

  const wrap = (children) => (
    <div style={{ position: 'relative', minHeight: '100vh', background: 'var(--bg-canvas)', overflow: 'hidden', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '40px 24px 64px' }}>
      <window.MarkWash opacity={0.08} size={620} pos={{ top: '-180px', left: '-160px' }} />
      <div style={{ position: 'relative', width: '100%', maxWidth: 680 }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 30 }}><window.PLogo height={20} /></div>
        {children}
      </div>
    </div>
  );

  if (done) {
    return wrap(
      <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-xl)', padding: '56px 40px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, boxShadow: 'var(--shadow-lg)' }}>
        <span style={{ width: 76, height: 76, borderRadius: '50%', background: 'var(--accent-soft)', border: '1px solid var(--border-accent)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--glow-soft)' }}>
          <window.PIcon n="check" s={36} color="var(--accent-bright)" stroke={2.2} />
        </span>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 38, color: 'var(--text-strong)', margin: 0 }}>You’re all set.</h2>
        <p style={{ fontFamily: 'var(--font-sans)', fontSize: 16, color: 'var(--text-muted)', maxWidth: 380, margin: 0, lineHeight: 1.6 }}>
          Thanks! Your brief is with the Mandera team. Your dashboard is now unlocked.
        </p>
        <Button variant="primary" size="lg" iconRight={<window.PIcon n="arrow-right" s={18} color="var(--ink-950)" />} onClick={() => go('app')}>Enter your portal</Button>
      </div>
    );
  }

  const renderField = (fld) => {
    if (fld.type === 'text') return <Input value={f[fld.key] || ''} onChange={(e) => set(fld.key, e.target.value)} placeholder={fld.hint || ''} />;
    if (fld.type === 'textarea') return (
      <textarea rows={4} value={f[fld.key] || ''} onChange={(e) => set(fld.key, e.target.value)} placeholder={fld.hint || ''}
        style={{ resize: 'vertical', padding: '12px 14px', background: 'var(--surface-sunken)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', color: 'var(--text-strong)', fontFamily: 'var(--font-sans)', fontSize: 15, outline: 'none' }}
        onFocus={(e) => e.target.style.borderColor = 'var(--accent)'} onBlur={(e) => e.target.style.borderColor = 'var(--border-default)'} />
    );
    if (fld.type === 'chips') {
      const val = f[fld.key];
      const isOn = (o) => fld.single ? val === o : Array.isArray(val) && val.includes(o);
      return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>{fld.options.map((o) => <Chip key={o} active={isOn(o)} onClick={() => toggle(fld.key, o, fld.single)}>{o}</Chip>)}</div>;
    }
    return null;
  };

  return wrap(
    <>
      <div style={{ marginBottom: 26 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <span className="mandera-eyebrow">Step {step + 1} of {total} · {isReview ? 'Review' : schema[step].section}</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>{pct}%</span>
        </div>
        <div style={{ height: 4, borderRadius: 'var(--radius-pill)', background: 'var(--surface-raised)', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: pct + '%', background: 'var(--grad-mark)', borderRadius: 'var(--radius-pill)', transition: 'width var(--dur-base) var(--ease-out)' }} />
        </div>
      </div>

      <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-xl)', padding: 36, boxShadow: 'var(--shadow-md)', display: 'flex', flexDirection: 'column', gap: 22 }}>
        {!isReview && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 22 }}>
            {schema[step].fields.map((fld) => (
              <div key={fld.key} style={{ flex: fld.half ? '1 1 calc(50% - 11px)' : '1 1 100%', minWidth: fld.half ? 180 : '100%' }}>
                <Field label={fld.label + (fld.required ? ' *' : '')} hint={fld.hint}>{renderField(fld)}</Field>
              </div>
            ))}
          </div>
        )}

        {isReview && (<>
          <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--text-strong)', margin: 0 }}>Quick review</h3>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text-muted)', margin: '-8px 0 0' }}>Anything left blank, we’ll explore together — you don’t have to fill in everything.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {schema.map((sec) => {
              const answered = sec.fields.filter((fld) => { const v = f[fld.key]; return Array.isArray(v) ? v.length : v; });
              return (
                <div key={sec.section} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span className="mandera-eyebrow">{sec.section}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-faint)' }}>{answered.length}/{sec.fields.length}</span>
                  </div>
                  {sec.fields.map((fld) => {
                    const v = f[fld.key]; const disp = Array.isArray(v) ? v.join(', ') : v;
                    return (
                      <div key={fld.key} style={{ display: 'flex', justifyContent: 'space-between', gap: 24, padding: '9px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                        <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text-muted)', maxWidth: 300 }}>{fld.label}</span>
                        <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600, color: disp ? 'var(--text-strong)' : 'var(--text-faint)', textAlign: 'right', maxWidth: 320 }}>{disp || '—'}</span>
                      </div>
                    );
                  })}
                </div>
              );
            })}
          </div>
          <Checkbox label="Everything looks right — share this brief with my Mandera team." checked={consent} onChange={setConsent} />
        </>)}

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
          <Button variant="ghost" onClick={() => step === 0 ? go('welcome') : setStep(step - 1)} iconLeft={<window.PIcon n="arrow-left" s={16} />}>
            {step === 0 ? 'Back' : 'Previous'}
          </Button>
          {!isReview
            ? <Button variant="primary" onClick={() => setStep(step + 1)} iconRight={<window.PIcon n="arrow-right" s={16} color="var(--ink-950)" />}>Continue</Button>
            : <Button variant="primary" disabled={!consent} onClick={submit} iconRight={<window.PIcon n="check" s={16} color="var(--ink-950)" />}>Submit brief</Button>}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Welcome, Onboarding, OnbChip: Chip, OnbField: Field });
