// Onboarding 3-step stepper

const { useState: useOb } = React;

function Onboarding({ onFinish }) {
  const [step, setStep] = useOb(1);
  const [orgName, setOrgName] = useOb('Acme, Inc.');
  const [slug, setSlug] = useOb('acme');
  const [env, setEnv] = useOb('dev');
  const [picked, setPicked] = useOb(new Set(['chatroom', 'pagevault']));
  const [installModalOpen, setInstallModalOpen] = useOb(false);
  const [installClient, setInstallClient] = useOb('claudecode');

  const togglePick = (id) => {
    const n = new Set(picked);
    n.has(id) ? n.delete(id) : n.add(id);
    setPicked(n);
  };

  const startInstall = (client) => {
    setInstallClient(client);
    setInstallModalOpen(true);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'var(--bg)',
      display: 'flex', flexDirection: 'column', zIndex: 200,
      overflow: 'auto',
    }}>
      {/* Header */}
      <div style={{
        padding: '20px 32px', borderBottom: '1px solid var(--border-subtle)',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <ParcleLogo/>
        <div style={{ flex: 1 }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {[1,2,3].map(n => (
            <div key={n} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: n < step ? 'var(--accent)' : n === step ? 'var(--surface)' : 'transparent',
                border: `1.5px solid ${n <= step ? 'var(--accent)' : 'var(--border)'}`,
                color: n < step ? 'var(--on-accent)' : n === step ? 'var(--accent)' : 'var(--text-tertiary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 500,
              }}>
                {n < step ? <Icons.Check size={11}/> : n}
              </div>
              {n < 3 && <div style={{ width: 40, height: 1.5, background: n < step ? 'var(--accent)' : 'var(--border)' }}/>}
            </div>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
        <button className="btn ghost" onClick={onFinish}>Skip to console →</button>
      </div>

      {/* Body */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '64px 32px' }}>
        <div style={{ width: 640 }}>
          {step === 1 && (
            <div>
              <div className="t-display-xl" style={{ marginBottom: 12 }}>Parcle.</div>
              <div className="t-h2 text-secondary" style={{ fontWeight: 400, marginBottom: 40 }}>One API for everything your org knows.</div>

              <Field label="Organization name">
                <input className="input" value={orgName} onChange={e => setOrgName(e.target.value)}/>
              </Field>
              <Field label="Your workspace URL">
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div className="mono text-tertiary">parcle.dev/</div>
                  <input className="input" value={slug} onChange={e => setSlug(e.target.value)} style={{ flex: 1 }}/>
                  <span className="chip success"><Icons.Check size={11}/> Available</span>
                </div>
              </Field>
              <Field label="Environment">
                <div style={{ display: 'flex', gap: 10 }}>
                  <PickCard checked={env === 'dev'} onClick={() => setEnv('dev')} title="Development" desc="Sandbox keys · no billing"/>
                  <PickCard checked={env === 'prod'} onClick={() => setEnv('prod')} title="Production" desc="Add later from Settings"/>
                </div>
              </Field>

              <button className="btn accent lg mt-24" onClick={() => setStep(2)}>
                Continue <Icons.ArrowR size={14}/>
              </button>
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="t-display" style={{ marginBottom: 8 }}>Connect your first sources</div>
              <div className="t-body text-secondary" style={{ marginBottom: 32 }}>Pick 1–3 to start. You can add the rest later.</div>

              <div className="t-micro text-tertiary" style={{ marginBottom: 12 }}>Suggested for you</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
                {['chatroom', 'pagevault', 'cloudbin', 'repohub'].map(id => {
                  const v = VENDORS[id];
                  const on = picked.has(id);
                  return (
                    <button key={id} onClick={() => togglePick(id)} style={{
                      padding: 14,
                      border: `1px solid ${on ? 'var(--accent)' : 'var(--border-subtle)'}`,
                      background: on ? 'var(--accent-muted)' : 'var(--surface)',
                      borderRadius: 10, textAlign: 'left',
                      display: 'flex', flexDirection: 'column', gap: 10, minHeight: 108,
                    }}>
                      <VendorLogo vendor={id} size={28}/>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{v.name}</div>
                        <div className="mono-sm mono text-tertiary">{CAT_LABEL_SHORT[v.glyph]}</div>
                      </div>
                      <div className="mono-sm mono" style={{ color: on ? 'var(--accent-text)' : 'var(--text-tertiary)' }}>
                        {on ? '✓ Selected' : '+ Add'}
                      </div>
                    </button>
                  );
                })}
              </div>
              <button className="btn ghost mt-16" style={{ color: 'var(--accent-text)' }}>Browse all 47 connectors →</button>

              {picked.size > 0 && (
                <div style={{ marginTop: 32 }}>
                  <div className="t-micro text-tertiary" style={{ marginBottom: 10 }}>Your selections · {picked.size}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {[...picked].map(id => (
                      <div key={id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: 'var(--surface)', border: '1px solid var(--border-subtle)', borderRadius: 8 }}>
                        <VendorLogo vendor={id} size={22} radius={6}/>
                        <span style={{ fontSize: 13, fontWeight: 500 }}>{VENDORS[id].name}</span>
                        <span className="mono-sm mono text-tertiary" style={{ flex: 1 }}>pending OAuth</span>
                        <StatusDot kind="syncing" size={6}/>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div style={{ display: 'flex', gap: 8, marginTop: 32 }}>
                <button className="btn" onClick={() => setStep(1)}>← Back</button>
                <button className="btn ghost" onClick={() => setStep(3)}>Skip for now</button>
                <div style={{ flex: 1 }}/>
                <button className="btn accent" onClick={() => setStep(3)}>Connect & continue →</button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <div className="t-display" style={{ marginBottom: 8 }}>Install Parcle into your AI client</div>
              <div className="t-body text-secondary" style={{ marginBottom: 32 }}>Pick a client below to drop the Parcle skill into it.</div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
                {[
                  { id: 'claudecode', name: 'Claude Code', official: true },
                  { id: 'codex',      name: 'Codex',       official: true },
                  { id: 'openclaw',   name: 'OpenClaw',    official: false },
                  { id: 'hermes',     name: 'Hermes',      official: false },
                ].map(c => (
                  <ClientCard key={c.id} client={c} onInstall={() => startInstall(c.id)}/>
                ))}
              </div>

              <div style={{ marginTop: 24, padding: 16, background: 'var(--bg)', borderRadius: 8, border: '1px solid var(--border-subtle)' }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>Using a different client or building from scratch?</div>
                <button className="btn ghost mt-8" style={{ color: 'var(--accent-text)', padding: 0 }}>
                  Generate a key manually → <span className="text-tertiary" style={{ fontWeight: 400 }}>(Settings → Keys)</span>
                </button>
              </div>

              <div style={{ display: 'flex', gap: 8, marginTop: 32 }}>
                <button className="btn" onClick={() => setStep(2)}>← Back</button>
                <div style={{ flex: 1 }}/>
                <button className="btn accent" onClick={onFinish}>Finish — take me in →</button>
              </div>
            </div>
          )}
        </div>
      </div>

      <InstallSkillModal
        open={installModalOpen}
        client={installClient}
        onClose={() => setInstallModalOpen(false)}/>
    </div>
  );
}

function ClientCard({ client, onInstall }) {
  return (
    <div style={{
      padding: 18,
      border: '1px solid var(--border-subtle)',
      background: 'var(--surface)',
      borderRadius: 10, display: 'flex', flexDirection: 'column', gap: 10, minHeight: 140,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          background: 'var(--text-primary)', color: 'var(--bg)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontFamily: "'Geist Mono', monospace",
        }}>{'>_'}</div>
        {client.official && (
          <span className="chip accent" style={{ fontSize: 10, height: 20 }}>official</span>
        )}
      </div>
      <div>
        <div className="t-h3">{client.name}</div>
      </div>
      <div style={{ marginTop: 'auto' }}>
        <button className="btn accent" style={{ width: '100%' }} onClick={onInstall}>Install</button>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div className="t-micro text-tertiary" style={{ marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}
function PickCard({ checked, onClick, title, desc }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, padding: 14, textAlign: 'left',
      border: `1px solid ${checked ? 'var(--accent)' : 'var(--border)'}`,
      background: checked ? 'var(--accent-muted)' : 'var(--surface)',
      borderRadius: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          width: 14, height: 14, borderRadius: '50%',
          border: `1.5px solid ${checked ? 'var(--accent)' : 'var(--border-strong)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {checked && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }}/>}
        </span>
        <span style={{ fontSize: 13, fontWeight: 500 }}>{title}</span>
      </div>
      <div className="t-small text-tertiary" style={{ marginTop: 4, marginLeft: 22 }}>{desc}</div>
    </button>
  );
}

function ParcleLogo() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
        <rect width="24" height="24" rx="6" fill="var(--text-primary)"/>
        <path d="M7 6h6a4 4 0 010 8H9v4H7z" stroke="var(--bg)" strokeWidth="1.8"/>
      </svg>
      <span style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>Parcle</span>
    </div>
  );
}

Object.assign(window, { Onboarding, ParcleLogo });
