// Post-signup onboarding wizard. Shown to brand-new workspace owners until
// they've either completed or skipped each of three steps:
//   1. Connect claude.ai (or any MCP client) to their workspace via OAuth.
//   2. Create a first project.
//   3. Optionally connect a VPS to run Claude Code on.
//
// Lives outside <AuthenticatedApp /> so it can sit between the auth gate and
// the main shell without polluting the rest of the app's hooks. Skip is
// persisted in localStorage as 'ws.onboarding.skipped' = '1'; once skipped
// the wizard never shows again on this browser. Re-opens via a button in
// the empty state of the project switcher (see projects.jsx).

function OnboardingWizard({ onDone }) {
  const [status, setStatus] = React.useState(null);
  const [step, setStep] = React.useState(1);
  const [error, setError] = React.useState(null);

  const refresh = React.useCallback(async () => {
    try {
      const r = await window.api('GET', '/api/me/onboarding-status');
      setStatus(r);
      // If the user navigates back into the wizard after completing some
      // steps elsewhere (e.g. created a project from the project switcher),
      // jump them to the next pending step automatically.
      if (!r.claudeAiConnected) setStep(1);
      else if (!r.hasProject) setStep(2);
      else setStep(3);
      return r;
    } catch (e) {
      setError(e?.message || 'No se pudo cargar el estado del onboarding.');
      return null;
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const skipAll = () => {
    // Scope by user id so dismissing the wizard on this account doesn't
    // leak the choice to other users on the same browser.
    try {
      const key = 'ws.onboarding.skipped.' + (window.ME?.id || '');
      if (window.ME?.id) localStorage.setItem(key, '1');
    } catch {}
    onDone && onDone();
  };

  if (!status) {
    return (
      <div style={_shellStyle}>
        <div style={{ padding: 40, color: 'var(--text-2)', fontSize: 13 }}>Cargando…</div>
      </div>
    );
  }

  return (
    <div style={_shellStyle}>
      <div style={_cardStyle}>
        <_Header current={step} status={status} onSkipAll={skipAll} />

        {step === 1 && (
          <Step1Claude
            status={status}
            onContinue={async () => { await refresh(); setStep(2); }}
            onSkip={() => setStep(2)}
          />
        )}
        {step === 2 && (
          <Step2Project
            status={status}
            onContinue={async () => { await refresh(); setStep(3); }}
            onSkip={() => setStep(3)}
          />
        )}
        {step === 3 && (
          <Step3Vps
            status={status}
            onContinue={() => onDone && onDone()}
            onSkip={() => onDone && onDone()}
          />
        )}

        {error && (
          <div style={{
            marginTop: 14, padding: '10px 12px', fontSize: 12,
            background: 'rgba(239,68,68,.10)', border: '1px solid rgba(239,68,68,.35)',
            color: 'var(--danger)', borderRadius: 6,
          }}>{error}</div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Header — title + step indicator + global skip
// ─────────────────────────────────────────────────────────────────────────
function _Header({ current, status, onSkipAll }) {
  const dot = (n, label, done) => (
    <div key={n} style={{ display: 'flex', alignItems: 'center', gap: 8, opacity: n === current ? 1 : 0.55 }}>
      <div style={{
        width: 22, height: 22, borderRadius: '50%',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: done ? '#10b981' : (n === current ? 'var(--accent)' : 'var(--bg-2)'),
        color: done || n === current ? 'white' : 'var(--text-2)',
        fontSize: 11, fontWeight: 700,
      }}>
        {done ? <Icon name="check" size={12} color="white" /> : n}
      </div>
      <span style={{ fontSize: 12, color: n === current ? 'var(--text-0)' : 'var(--text-2)' }}>{label}</span>
    </div>
  );
  const steps = [
    { n: 1, label: 'Conectar Claude.ai', done: status.claudeAiConnected },
    { n: 2, label: 'Primer proyecto', done: status.hasProject },
    { n: 3, label: 'Conectar VPS', done: status.hasVps },
  ];
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text-0)' }}>
          Bienvenido a Workspace 👋
        </div>
        <button className="btn-reset" onClick={onSkipAll}
          style={{ fontSize: 11.5, color: 'var(--text-3)' }}>
          Saltar todo
        </button>
      </div>
      <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
        {steps.map((s) => dot(s.n, s.label, s.done))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Step 1 — Connect claude.ai (or any MCP client) to the workspace
// ─────────────────────────────────────────────────────────────────────────
function Step1Claude({ status, onContinue, onSkip }) {
  const [copied, setCopied] = React.useState(false);
  const [checking, setChecking] = React.useState(false);
  const [recheckMsg, setRecheckMsg] = React.useState(null);
  const url = status.mcpUrl || `${window.location.origin}/mcp`;

  const copy = async () => {
    try { await navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    catch { /* ignore — clipboard might be blocked in some contexts */ }
  };

  const recheck = async () => {
    setChecking(true);
    setRecheckMsg(null);
    try {
      const r = await window.api('GET', '/api/me/onboarding-status');
      if (r.claudeAiConnected) {
        onContinue && onContinue();
      } else {
        setRecheckMsg('Aún no detectamos la conexión. Asegúrate de haber autorizado el connector en claude.ai.');
      }
    } catch (e) {
      setRecheckMsg(e?.message || 'Error al verificar.');
    } finally {
      setChecking(false);
    }
  };

  if (status.claudeAiConnected) {
    return (
      <_StepLayout
        title="Claude.ai conectado ✓"
        sub="Tu workspace ya está disponible desde claude.ai. Puedes pedirle a Claude que cree tareas, busque docs, agregue colaboradores, etc."
        primaryLabel="Continuar"
        onPrimary={onContinue}
      />
    );
  }

  return (
    <_StepLayout
      title="Conecta tu cuenta de Claude.ai"
      sub="Esto te permite hablar con tu workspace desde claude.ai. Vas a poder pedirle a Claude que cree tareas, edite documentos del Vault, busque información, agregue colaboradores y más, sin salir de la app de claude.ai."
    >
      <ol style={{ paddingLeft: 18, fontSize: 13, color: 'var(--text-1)', lineHeight: 1.7, margin: '0 0 12px 0' }}>
        <li>Abre <a href="https://claude.ai/settings/connectors" target="_blank" rel="noreferrer"
          style={{ color: 'var(--accent)' }}>claude.ai → Settings → Connectors</a>.</li>
        <li>Click en <strong>"Add custom connector"</strong>.</li>
        <li>Pega esta URL como dirección del servidor MCP:
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '10px 12px', background: 'var(--bg-2)',
            border: '1px solid var(--border)', borderRadius: 6,
            margin: '8px 0 4px 0',
          }}>
            <span className="mono" style={{ flex: 1, fontSize: 12, color: 'var(--text-1)', overflow: 'hidden', textOverflow: 'ellipsis' }}>{url}</span>
            <button className="btn-reset" onClick={copy} type="button"
              style={{
                padding: '6px 10px', fontSize: 11.5, fontWeight: 500,
                background: copied ? '#10b981' : 'var(--accent)', color: 'white',
                borderRadius: 4,
              }}>
              {copied ? '¡Copiado!' : 'Copiar'}
            </button>
          </div>
        </li>
        <li>Una vez agregado, dale click a <strong>"Conectar"</strong> dentro de la sección de <em>MCP personalizados</em>. Te va a mandar a esta app a autorizar el acceso a tu workspace.</li>
        <li>Aprueba la autorización y vuelve aquí.</li>
      </ol>
      <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 14, lineHeight: 1.6 }}>
        Cuando termines, pulsa <strong>"Ya lo conecté"</strong> y verificamos la conexión.
      </div>

      {recheckMsg && (
        <div style={{
          padding: '8px 12px', fontSize: 12, marginBottom: 12,
          background: 'rgba(245,158,11,.10)', border: '1px solid rgba(245,158,11,.35)',
          color: '#f59e0b', borderRadius: 6,
        }}>{recheckMsg}</div>
      )}

      <_StepActions
        primaryLabel={checking ? 'Verificando…' : 'Ya lo conecté'}
        onPrimary={recheck}
        primaryDisabled={checking}
        secondaryLabel="Saltar este paso"
        onSecondary={onSkip}
      />
    </_StepLayout>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Step 2 — Create first project
// ─────────────────────────────────────────────────────────────────────────
function Step2Project({ status, onContinue, onSkip }) {
  const [slug, setSlug] = React.useState('');
  const [name, setName] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  // Auto-derive slug from name as the user types, until they edit slug manually.
  const [slugTouched, setSlugTouched] = React.useState(false);
  React.useEffect(() => {
    if (!slugTouched) {
      setSlug(name.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30));
    }
  }, [name, slugTouched]);

  const slugValid = /^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])?$/.test(slug);
  const canSubmit = slugValid && name.trim().length > 0 && !submitting;

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!canSubmit) return;
    setError(null);
    setSubmitting(true);
    try {
      await window.createProject({ id: slug, name: name.trim(), githubRepo: null, includeTlead: false, vpsId: null });
      // Reload PROJECTS so the rest of the app sees the new one.
      try { await window.loadProjects?.(); } catch {}
      onContinue && onContinue();
    } catch (err) {
      setError(err?.body?.error || err?.message || 'Error al crear el proyecto.');
    } finally {
      setSubmitting(false);
    }
  };

  if (status.hasProject) {
    return (
      <_StepLayout
        title="Ya tienes un proyecto ✓"
        sub="Avancemos al siguiente paso."
        primaryLabel="Continuar"
        onPrimary={onContinue}
      />
    );
  }

  return (
    <_StepLayout
      title="Crea tu primer proyecto"
      sub="Un proyecto agrupa tareas, docs del Vault, fases, sesiones de Claude Code y archivos. Después puedes asignarlo a un VPS para correr Claude Code remoto."
    >
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <_Field label="Nombre">
          <input value={name} onChange={(e) => setName(e.target.value)}
            placeholder="Mi proyecto"
            autoFocus
            style={_inputStyle(true)} />
        </_Field>
        <_Field label="Identificador" hint="Letras minúsculas, números y guiones. 2–30 caracteres.">
          <input value={slug} onChange={(e) => { setSlugTouched(true); setSlug(e.target.value); }}
            placeholder="mi-proyecto"
            className="mono"
            style={_inputStyle(slugValid || slug === '')} />
        </_Field>

        {error && (
          <div style={{
            padding: '8px 12px', fontSize: 12,
            background: 'rgba(239,68,68,.10)', border: '1px solid rgba(239,68,68,.35)',
            color: 'var(--danger)', borderRadius: 6,
          }}>{error}</div>
        )}

        <_StepActions
          primaryLabel={submitting ? 'Creando…' : 'Crear y continuar'}
          onPrimary={submit}
          primaryDisabled={!canSubmit}
          secondaryLabel="Saltar este paso"
          onSecondary={onSkip}
        />
      </form>
    </_StepLayout>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Step 3 — Connect VPS (optional)
// ─────────────────────────────────────────────────────────────────────────
function Step3Vps({ status, onContinue, onSkip }) {
  if (status.hasVps) {
    return (
      <_StepLayout
        title="VPS conectado ✓"
        sub="Tu workspace ya tiene un VPS donde Claude Code puede correr remotamente."
        primaryLabel="Entrar al workspace"
        onPrimary={onContinue}
      />
    );
  }

  return (
    <_StepLayout
      title="¿Quieres conectar un VPS?"
      sub="Para correr sesiones de Claude Code remotamente desde tu workspace, conecta un servidor donde se vaya a ejecutar el CLI de Claude. Puedes hacerlo después desde el menú del proyecto si prefieres explorar primero."
    >
      <div style={{
        padding: 14, fontSize: 12, marginBottom: 14, lineHeight: 1.6,
        background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text-1)',
      }}>
        <strong style={{ color: 'var(--text-0)' }}>Lo que vas a necesitar:</strong>
        <ul style={{ paddingLeft: 18, margin: '6px 0 0 0' }}>
          <li>IP pública del VPS y puerto SSH (22 por defecto).</li>
          <li>Contraseña root <em>(la usamos una sola vez para deployar una clave SSH; no se guarda)</em>.</li>
          <li>Mínimo 2 GB de RAM y 10 GB libres en disco.</li>
        </ul>
      </div>

      <_StepActions
        primaryLabel="Conectar VPS ahora"
        onPrimary={() => {
          // Stash a flag so AuthenticatedApp opens the VPS manager as soon
          // as it mounts. Calling window.openVpsManager() here is a no-op
          // because <VpsManagerHost /> doesn't exist yet — the wizard owns
          // the screen, the host lives inside <AuthenticatedApp />.
          try { localStorage.setItem('ws.openVpsAfterWizard', '1'); } catch {}
          onContinue && onContinue();
        }}
        secondaryLabel="Después"
        onSecondary={onSkip}
      />
    </_StepLayout>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Layout helpers
// ─────────────────────────────────────────────────────────────────────────
function _StepLayout({ title, sub, children, primaryLabel, onPrimary }) {
  return (
    <div>
      <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text-0)', marginBottom: 6 }}>{title}</div>
      <div style={{ fontSize: 13, color: 'var(--text-1)', lineHeight: 1.6, marginBottom: 18 }}>{sub}</div>
      {children}
      {!children && primaryLabel && (
        <_StepActions primaryLabel={primaryLabel} onPrimary={onPrimary} />
      )}
    </div>
  );
}

function _StepActions({ primaryLabel, onPrimary, primaryDisabled, secondaryLabel, onSecondary }) {
  return (
    <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
      {secondaryLabel && (
        <button type="button" className="btn-reset" onClick={onSecondary}
          style={{
            padding: '10px 16px', fontSize: 13, fontWeight: 500,
            background: 'transparent', color: 'var(--text-2)',
            border: '1px solid var(--border)', borderRadius: 6,
          }}>
          {secondaryLabel}
        </button>
      )}
      <button type="button" className="btn-reset" onClick={onPrimary} disabled={primaryDisabled}
        style={{
          padding: '10px 18px', fontSize: 13, fontWeight: 600,
          background: primaryDisabled ? 'var(--bg-2)' : 'var(--accent)',
          color: primaryDisabled ? 'var(--text-3)' : 'white',
          borderRadius: 6,
          cursor: primaryDisabled ? 'not-allowed' : 'pointer',
        }}>
        {primaryLabel}
      </button>
    </div>
  );
}

function _Field({ label, hint, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-2)', textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 4 }}>{hint}</div>}
    </label>
  );
}

function _inputStyle(valid) {
  return {
    width: '100%', padding: '10px 12px',
    background: 'var(--bg-1)',
    border: `1px solid ${valid ? 'var(--border)' : 'rgba(239,68,68,.5)'}`,
    borderRadius: 6,
    color: 'var(--text-0)', fontSize: 14, outline: 'none',
  };
}

const _shellStyle = {
  height: '100vh', width: '100vw',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  background: 'var(--bg-0)',
  padding: 16,
};
const _cardStyle = {
  width: 580, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto',
  padding: 32, background: 'var(--bg-1)',
  border: '1px solid var(--border)', borderRadius: 12,
  boxShadow: '0 24px 48px rgba(0,0,0,.5)',
};

window.OnboardingWizard = OnboardingWizard;
