/* Onboarding — wired to live /api/onboarding/status. */

function OnboardingScreen() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;
    apiFetch('/api/onboarding/status')
      .then((res) => { if (!cancelled) { setData(res); setLoading(false); } })
      .catch((err) => { if (!cancelled) { setError(err.message); setLoading(false); } });
    return () => { cancelled = true; };
  }, []);

  const steps = (data && (data.steps || data.checklist || [])) || [];
  const completed = data && (data.onboarding_completed || data.completed || false);
  const currentStep = data && (data.onboarding_step || data.current_step || null);

  /* Each step's CTA routes to where the work actually happens. The
     existing onboarding API doesn't track granular step completion
     yet, so we use the heuristic below (route to the page that
     completes the step + use real data presence to mark done). */
  const fallback = [
    { id: 'site',     title: 'Add your first site',          desc: 'Tell Slate where this aquarium is.',              cta: 'Add site',     route: '#orgs' },
    { id: 'zones',    title: 'Define your zones',            desc: 'Group screens by physical area.',                  cta: 'Set up zones', route: '#zones' },
    { id: 'screen',   title: 'Provision a screen',           desc: 'Pair your first display device.',                  cta: 'Pair a screen',route: '#displays' },
    { id: 'species',  title: 'Add species to a zone',        desc: 'Pick from the global library or create your own.', cta: 'Browse library', route: '#library' },
    { id: 'campaign', title: 'Schedule your first campaign', desc: 'Run a takeover, overlay, or story.',               cta: 'New campaign',  route: '#campaigns' },
    { id: 'team',     title: 'Invite your team',             desc: 'Add aquarists, designers, and operators.',         cta: 'Invite people', route: '#users' },
  ];
  const checklist = steps.length > 0 ? steps : fallback.map((s) => ({
    ...s,
    done: completed || (currentStep && fallback.findIndex((f) => f.id === currentStep) > fallback.findIndex((f) => f.id === s.id)),
  }));
  const completedCount = checklist.filter((s) => s.done || s.completed).length;
  const pct = checklist.length > 0 ? Math.round((completedCount / checklist.length) * 100) : 0;

  return (
    <div className="ob-content">
      <header style={{ marginBottom: 8 }}>
        <div className="aq-eyebrow">
          <span>{(Auth.getUser() || {}).org_name || 'Slate'}</span>
          <span className="aq-sep">·</span>
          <span>First-run setup</span>
        </div>
        <h1 style={{
          fontFamily: 'var(--aq-ff-display)', fontSize: 32, fontWeight: 500,
          letterSpacing: '-0.018em', color: 'var(--aq-text)', margin: '8px 0 4px',
        }}>Welcome to Slate</h1>
        <p style={{ fontSize: 14, color: 'var(--aq-text-dim)', margin: 0, maxWidth: 600 }}>
          Six steps to a fully wired workspace. We'll mark each as done automatically as you complete it.
        </p>
      </header>

      {loading && <div style={{ padding: 40, textAlign: 'center', color: 'var(--aq-text-faint)' }}>Loading your progress…</div>}
      {error && (
        <div style={{
          padding: '10px 14px',
          background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
          border: '1px solid color-mix(in srgb, var(--aq-danger) 30%, transparent)',
          borderRadius: 6, color: 'var(--aq-danger)', fontSize: 12,
        }}>{error}</div>
      )}

      {!loading && !error && (
        <>
          <section className="x-card" style={{ padding: 20, marginTop: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <div>
                <div className="x-eyebrow">Setup progress</div>
                <div style={{ fontFamily: 'var(--aq-ff-display)', fontSize: 22, fontWeight: 500, color: 'var(--aq-text)', marginTop: 4 }}>
                  {completedCount} of {checklist.length}
                </div>
              </div>
              <div style={{ fontFamily: 'var(--aq-ff-display)', fontSize: 36, fontWeight: 500, color: 'var(--aq-accent)' }}>{pct}%</div>
            </div>
            <div className="x-meter-bar" style={{ height: 8 }}>
              <div className="x-meter-fill" style={{ width: `${pct}%` }} />
            </div>
          </section>

          <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
            {checklist.map((s, i) => {
              const done = s.done || s.completed;
              return (
                <li key={s.id || i} className="x-card" style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 16 }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: '50%',
                    background: done ? 'color-mix(in srgb, var(--aq-success) 18%, transparent)' : 'var(--aq-surface-2)',
                    border: `1px solid ${done ? 'color-mix(in srgb, var(--aq-success) 40%, transparent)' : 'var(--aq-line)'}`,
                    color: done ? 'var(--aq-success)' : 'var(--aq-text-faint)',
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                    fontFamily: 'var(--aq-ff-display)', fontSize: 12, fontWeight: 600,
                  }}>{done ? <Icon name="check" size={14} /> : (i + 1)}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 14, color: 'var(--aq-text)', fontWeight: 500,
                      textDecoration: done ? 'line-through' : 'none',
                      opacity: done ? 0.7 : 1,
                    }}>{s.title || s.label}</div>
                    {s.desc && <div style={{ fontSize: 12, color: 'var(--aq-text-faint)', marginTop: 2 }}>{s.desc}</div>}
                  </div>
                  <button
                    className={done ? 'x-btn ghost sm' : 'x-btn'}
                    disabled={done}
                    onClick={() => {
                      /* Route to the step's destination. fallback rows
                         carry an explicit `route`; backend-driven steps
                         may instead carry `link` or `route` fields. */
                      const dest = s.route || s.link || (() => {
                        const f = fallback.find((x) => x.id === s.id);
                        return f && f.route;
                      })();
                      if (dest) window.location.hash = dest;
                    }}
                  >
                    {done ? 'Completed' : (s.cta || 'Open')}
                  </button>
                </li>
              );
            })}
          </ul>
        </>
      )}
    </div>
  );
}

window.OnboardingScreen = OnboardingScreen;
