// onboarding.jsx — First-run empty-state hero for the dashboard
//
// Renders a big "let's get started" hero ABOVE the dashboard chrome when:
//   localStorage.getItem('astro:onboarding-dismissed') !== '1'  AND
//   the user explicitly enables first-run preview via Tweaks (so demo data
//   doesn't accidentally trigger it for everyone).
//
// State: window.__rsOnboarding = { active, dismiss(), reset() }
// Trigger: window.dispatchEvent(new CustomEvent('astro-onboarding-toggle', {detail:{active:true|false}}))
//
// Three tiles:
//   1. DROP A FILE       — opens bulk-import
//   2. PASTE A SONG      — opens a 1-line quick-paste sheet → New Work modal
//   3. IMPORT FROM SPOTIFY — opens DSP analytics import w/ Spotify adapter
//
// Plus a "or browse the demo catalog →" escape hatch.

(function () {
  const { useState, useEffect, useMemo } = React;

  const KEY_DISMISSED = 'astro:onboarding-dismissed';
  const KEY_ACTIVE    = 'astro:onboarding-active'; // dev/preview override

  // ── State management ──────────────────────────────────────────────
  function isActive() {
    if (typeof localStorage === 'undefined') return false;
    if (localStorage.getItem(KEY_ACTIVE) === '1') return true;
    return false;
  }
  function dismiss() {
    try {
      localStorage.setItem(KEY_DISMISSED, '1');
      localStorage.removeItem(KEY_ACTIVE);
    } catch {}
    window.dispatchEvent(new CustomEvent('astro-onboarding-changed'));
  }
  function activate() {
    try {
      localStorage.setItem(KEY_ACTIVE, '1');
      localStorage.removeItem(KEY_DISMISSED);
    } catch {}
    window.dispatchEvent(new CustomEvent('astro-onboarding-changed'));
  }

  window.__rsOnboarding = { isActive, dismiss, activate };

  // ── Hero ───────────────────────────────────────────────────────────
  function OnboardingHero({ go, firstName }) {
    const [tick, setTick] = useState(0);
    useEffect(() => {
      const re = () => setTick(t => t + 1);
      window.addEventListener('astro-onboarding-changed', re);
      return () => window.removeEventListener('astro-onboarding-changed', re);
    }, []);
    const active = useMemo(() => isActive(), [tick]);
    if (!active) return null;

    const name = firstName || 'there';

    const Tile = ({ tag, title, desc, cta, onClick, accent, mono }) => (
      <button
        onClick={onClick}
        style={{
          appearance: 'none', border: '1px solid var(--rule)', background: '#fff',
          padding: '28px 26px 24px', textAlign: 'left', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', gap: 14, minHeight: 240,
          position: 'relative', transition: 'transform .18s ease, border-color .18s ease',
        }}
        onMouseEnter={e => {
          e.currentTarget.style.transform = 'translateY(-3px)';
          e.currentTarget.style.borderColor = accent;
        }}
        onMouseLeave={e => {
          e.currentTarget.style.transform = 'translateY(0)';
          e.currentTarget.style.borderColor = 'var(--rule)';
        }}
      >
        <div className="ff-mono upper" style={{
          fontSize: 9, letterSpacing: '.18em', color: accent,
        }}>{tag}</div>
        <div style={{
          fontFamily: mono ? 'var(--ff-mono)' : 'inherit',
          fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em',
          color: 'var(--ink-1)', lineHeight: 1.15,
        }}>
          {title}
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, flex: 1 }}>
          {desc}
        </div>
        <div className="ff-mono upper" style={{
          fontSize: 10, letterSpacing: '.14em', color: accent,
          paddingTop: 8, borderTop: '1px solid var(--rule-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span>{cta}</span>
          <span>↗</span>
        </div>
      </button>
    );

    return (
      <section style={{
        marginBottom: 36, paddingBottom: 36,
        borderBottom: '1px solid var(--rule)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 28, marginBottom: 28 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="ff-mono upper" style={{
              fontSize: 10, letterSpacing: '.18em', color: 'var(--ink-3)', marginBottom: 14,
            }}>
              First run · welcome
            </div>
            <h1 style={{
              margin: 0, fontSize: 56, letterSpacing: '-0.03em', fontWeight: 500,
              lineHeight: 1.05, maxWidth: 900,
            }}>
              Welcome, {name}.<br />
              <span style={{ color: 'var(--ink-3)' }}>Let's bring in your catalog.</span>
            </h1>
            <p style={{
              marginTop: 22, fontSize: 15, color: 'var(--ink-2)', lineHeight: 1.6, maxWidth: 680,
            }}>
              Pick the door that matches what you have on hand. You can always do the others later —
              and nothing here commits until you say so.
            </p>
          </div>
          <button
            onClick={() => { dismiss(); }}
            className="ff-mono upper"
            title="Dismiss this onboarding hero"
            style={{
              fontSize: 10, letterSpacing: '.14em', color: 'var(--ink-3)',
              background: 'transparent', border: '1px solid var(--rule)',
              padding: '10px 14px', cursor: 'pointer', whiteSpace: 'nowrap',
            }}
          >
            Skip · use demo data
          </button>
        </div>

        {/* Three tiles */}
        <div style={{
          display: 'grid', gap: 16,
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
        }}>
          <Tile
            tag="01 · UPLOAD"
            title="Drop a file"
            desc="CSV, XLSX, DDEX, CWR, JSON. We'll sniff the format, map the columns, and validate before anything is committed."
            cta="Open bulk import"
            accent="oklch(0.55 0.13 265)"
            onClick={() => go && go('bulk-import')}
          />
          <Tile
            tag="02 · TYPE"
            title="Paste a song"
            desc="Just title + writer. We'll fill in the rest from your existing data and let you complete it later. The fastest possible first entry."
            cta="Quick add a work"
            accent="oklch(0.50 0.12 145)"
            onClick={() => window.dispatchEvent(new CustomEvent('astro-add-song', { detail: { quick: true } }))}
          />
          <Tile
            tag="03 · CONNECT"
            title="Import from Spotify"
            desc="Drop a Spotify-for-Artists export — Trends, Audience, Songwriter — or any of 18 DSP adapters across 12 platforms. Auto-mapped, audit-ready."
            cta="Open DSP import"
            accent="oklch(0.58 0.14 60)"
            onClick={() => go && go('dsp-import')}
          />
        </div>

        {/* Footer escape hatch */}
        <div style={{
          marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--rule-soft)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          flexWrap: 'wrap', gap: 12,
        }}>
          <div className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5 }}>
            Or browse the demo catalog —{' '}
            <button onClick={() => go && go('catalog')} className="ff-mono"
              style={{ background: 'transparent', border: 0, color: 'var(--ink-1)', textDecoration: 'underline', cursor: 'pointer', fontSize: 11 }}>
              553 works, 1,200 recordings →
            </button>
          </div>
          <div className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.16em', color: 'var(--ink-3)' }}>
            Need help? Press <kbd style={{
              fontFamily: 'var(--ff-mono)', fontSize: 10, padding: '2px 6px',
              border: '1px solid var(--rule)', borderRadius: 2, marginLeft: 4,
            }}>⌘K</kbd>
          </div>
        </div>
      </section>
    );
  }

  window.OnboardingHero = OnboardingHero;
})();
