// components/Hero.jsx — Hero scroll-telling con terminale animato
// Prima vista: grande titolo editoriale + terminale che "compila" la bio di Federico

const rcTokens = {
  bg: '#e8e3d8',
  bgDark: '#353333',
  ink: '#1a1614',
  inkDark: '#e8e3d8',
  accent: '#d4431e',
  dim: '#5a5a5a',
  line: '#1a1614',
  lineDark: '#3a342e',
  panel: '#f0ebdf',
  panelDark: '#1c1816',
  serif: "'Fraunces', 'Playfair Display', Georgia, serif",
  mono: "'JetBrains Mono', 'IBM Plex Mono', monospace",
  sans: "'Inter', system-ui, sans-serif",
};
window.rcTokens = rcTokens;

// ─────────────────────────────────────────────────────────────
// Top navigation (stile LK: logo a sinistra, menu numerato a destra)
// ─────────────────────────────────────────────────────────────
function TopNav({ theme, onToggleTheme }) {
  const isDark = theme === 'dark';
  const ink = isDark ? rcTokens.ink : rcTokens.ink;
  const dim = rcTokens.dim;
  const line = isDark ? rcTokens.lineDark : rcTokens.line;

  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: 'clamp(12px, 3vw, 18px) clamp(16px, 6vw, 80px)',
      fontFamily: rcTokens.mono, fontSize: 'clamp(9px, 2vw, 11px)', letterSpacing: 2, textTransform: 'uppercase',
      color: isDark ? '#000000' : rcTokens.ink,
      background: 'rgba(232, 227, 216, 0.75)',
      backdropFilter: 'blur(12px)',
      borderBottom: `1px solid rgba(26, 22, 20, 0.1)`,
      transition: 'all 0.3s ease',
      gap: 'clamp(12px, 4vw, 40px)',
      flexWrap: 'wrap',
    }}>
      <div style={{ fontWeight: 700, whiteSpace: 'nowrap' }}>F<span style={{ color: rcTokens.accent }}>.</span>M<span style={{ color: rcTokens.accent }}>.</span></div>
      <div style={{ display: 'flex', gap: 'clamp(12px, 2vw, 28px)', flexWrap: 'wrap', justifyContent: 'center', flex: 1 }}>
        {[['01', 'bio'], ['02', 'what'], ['03', 'skills'], ['04', 'stack'], ['05', 'contattami']].map(([n, l]) => (
          <a key={n} href={`#${l}`} style={{
            color: 'inherit', textDecoration: 'none', display: 'flex', gap: 'clamp(4px, 1vw, 6px)',
            fontSize: 'clamp(9px, 2vw, 11px)', whiteSpace: 'nowrap',
          }}>
            <span style={{ opacity: 0.5, display: 'none' }}>{n}</span>
            <span>{l}</span>
          </a>
        ))}
      </div>
      <button onClick={onToggleTheme} style={{
        background: 'transparent', border: 'none', color: isDark ? '#000000' : rcTokens.ink,
        fontFamily: rcTokens.serif, fontSize: 'clamp(18px, 4vw, 24px)', cursor: 'pointer',
        padding: 'clamp(8px, 2vw, 12px)', whiteSpace: 'nowrap', fontWeight: 700,
      }}>
        {isDark ? '☼' : '☾'}
      </button>
    </nav>
  );
}

// ─────────────────────────────────────────────────────────────
// Loader / Intro — "0% → 100%" con nome che emerge (LK-style)
// ─────────────────────────────────────────────────────────────
function Loader({ onDone }) {
  const [pct, setPct] = React.useState(0);
  const [gone, setGone] = React.useState(false);

  React.useEffect(() => {
    let p = 0;
    const id = setInterval(() => {
      p += Math.random() * 8 + 2;
      if (p >= 100) { p = 100; clearInterval(id); setTimeout(() => { setGone(true); onDone?.(); }, 500); }
      setPct(Math.floor(p));
    }, 60);
    return () => clearInterval(id);
  }, []);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100, background: rcTokens.bg,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      padding: '0 6vw 6vh', pointerEvents: gone ? 'none' : 'auto',
      transform: gone ? 'translateY(-100%)' : 'translateY(0)',
      transition: 'transform 0.9s cubic-bezier(0.76, 0, 0.24, 1)',
    }}>
      <div style={{
        fontFamily: rcTokens.serif, fontSize: 'clamp(80px, 18vw, 280px)',
        lineHeight: 0.85, letterSpacing: -8, fontWeight: 500,
      }}>
        {pct}<span style={{ color: rcTokens.accent, fontSize: '0.5em' }}>%</span>
      </div>
      <div style={{
        fontFamily: rcTokens.mono, fontSize: 11, letterSpacing: 2, color: rcTokens.dim,
        textTransform: 'uppercase', textAlign: 'right',
      }}>
        loading<br/>
        <span style={{ color: rcTokens.accent }}>federicomolinaro.it</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Hero — grande titolo editoriale + terminale con typewriter
// ─────────────────────────────────────────────────────────────
function Terminal({ started, theme }) {
  const isDark = theme === 'dark';
  const lines = [
    { kind: 'cmd', text: 'whoami' },
    { kind: 'out', text: 'federico.molinaro' },
    { kind: 'out', text: 'senior software architect' },
    { kind: 'cmd', text: 'cat ./stack.json' },
    { kind: 'json', text: '{\n  "web":    ["angular", "react", "next.js"],\n  "mobile": ["flutter", "xamarin", "java"],\n  "gis":    ["postgis", "geoserver", "here"],\n  "ops":    ["docker", "ci/cd", "mqtt"],\n  "ai":     "strumento, non religione"\n}' },
    { kind: 'cmd', text: 'status --verbose' },
    { kind: 'ok', text: '● open to collaborate' },
  ];

  const [shown, setShown] = React.useState([]);
  const [typing, setTyping] = React.useState('');
  const [lineIdx, setLineIdx] = React.useState(0);

  React.useEffect(() => {
    if (!started) return;
    if (lineIdx >= lines.length) return;
    const full = lines[lineIdx].text;
    let i = 0;
    const speed = lines[lineIdx].kind === 'cmd' ? 40 : lines[lineIdx].kind === 'json' ? 8 : 16;
    const id = setInterval(() => {
      i++;
      setTyping(full.slice(0, i));
      if (i >= full.length) {
        clearInterval(id);
        setTimeout(() => {
          setShown(prev => [...prev, lines[lineIdx]]);
          setTyping('');
          setLineIdx(idx => idx + 1);
        }, lines[lineIdx].kind === 'cmd' ? 200 : 400);
      }
    }, speed);
    return () => clearInterval(id);
  }, [lineIdx, started]);

  const renderLine = (ln, i, isTyping) => {
    const outputColor = isDark ? '#000000' : rcTokens.ink;
    if (ln.kind === 'cmd') {
      return <div key={i} style={{ color: rcTokens.dim }}>
        <span style={{ color: rcTokens.accent }}>$ </span>{ln.text}
        {isTyping && <span className="rc-cursor"/>}
      </div>;
    }
    if (ln.kind === 'ok') {
      return <div key={i} style={{ color: rcTokens.accent }}>{ln.text}{isTyping && <span className="rc-cursor"/>}</div>;
    }
    if (ln.kind === 'json') {
      return <pre key={i} style={{ margin: 0, color: outputColor, fontFamily: 'inherit', fontSize: 'inherit', whiteSpace: 'pre-wrap' }}>{ln.text}{isTyping && <span className="rc-cursor"/>}</pre>;
    }
    return <div key={i} style={{ color: outputColor }}>{ln.text}{isTyping && <span className="rc-cursor"/>}</div>;
  };

  const currentLine = lineIdx < lines.length ? { ...lines[lineIdx], text: typing } : null;

  return (
    <div style={{
      fontFamily: rcTokens.mono, fontSize: 'clamp(11px, 2vw, 13px)', lineHeight: 1.7,
      background: 'transparent', padding: 'clamp(16px, 4vw, 24px) 0',
      minHeight: 320,
    }}>
      <div style={{
        fontSize: 'clamp(8px, 2vw, 10px)', color: rcTokens.dim, letterSpacing: 1, marginBottom: 'clamp(10px, 2vw, 14px)',
        display: 'flex', justifyContent: 'space-between', borderBottom: `1px solid ${rcTokens.line}`, paddingBottom: 'clamp(8px, 2vw, 10px)',
        overflow: 'auto',
      }}>
        <span style={{ whiteSpace: 'nowrap' }}>◉ ◉ ◉ &nbsp; federico@macbook ~ %</span>
        <span style={{ whiteSpace: 'nowrap' }}>zsh · 80×24</span>
      </div>
      {shown.map((ln, i) => renderLine(ln, i, false))}
      {currentLine && renderLine(currentLine, 'cur', true)}
    </div>
  );
}

function Hero({ ready, theme }) {
  const isDark = theme === 'dark';
  const [started, setStarted] = React.useState(false);
  React.useEffect(() => {
    if (ready) {
      const t = setTimeout(() => setStarted(true), 800);
      return () => clearTimeout(t);
    }
  }, [ready]);

  return (
    <section id="bio" data-screen-label="01 hero" style={{
      minHeight: '100vh', padding: 'clamp(100px, 12vw, 140px) clamp(16px, 6vw, 80px) clamp(40px, 8vw, 60px)', position: 'relative',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}>
      {/* Meta top */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 'clamp(12px, 4vw, 20px)',
        fontFamily: rcTokens.mono, fontSize: 'clamp(8px, 2vw, 10px)', letterSpacing: 2, color: isDark ? rcTokens.inkDark : rcTokens.dim,
        textTransform: 'uppercase', marginBottom: 'clamp(24px, 4vw, 40px)',
      }}>
        <span>(01) — Index</span>
        <span style={{ textAlign: 'center' }}>Rev. 01 / 04.2026</span>
        <span style={{ textAlign: 'right', color: rcTokens.accent }}>● Available</span>
      </div>

      {/* Main grid: titolo enorme + terminale affiancato */}
      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 'clamp(40px, 8vw, 60px)', alignItems: 'start' }} className="rc-hero-grid">
        <div>
          <h1 style={{
            fontFamily: rcTokens.serif,
            fontSize: 'clamp(48px, 10vw, 220px)',
            lineHeight: 1.0, letterSpacing: -4, fontWeight: 500,
            margin: 0,
          }}>
            <span className="rc-chars in" style={{ display: 'block' }} data-split="char">Federico</span>
            <span className="rc-chars in" style={{ display: 'inline', fontStyle: 'italic', fontWeight: 400 }} data-split="char">
              Molinaro
            </span><span style={{ color: rcTokens.accent, fontStyle: 'italic', fontWeight: 400 }}>.</span>
          </h1>
          <div data-reveal style={{ '--reveal-delay': '0.6s',
            marginTop: 'clamp(16px, 4vw, 28px)', maxWidth: 520, fontSize: 'clamp(14px, 3vw, 17px)', lineHeight: 1.55,
          }}>
            Software architect italiano. Costruisco <b>web app</b>, <b>mobile</b> e <b>interfacce</b> da oltre vent'anni — e mi diverto a portare l'<b>AI</b> dentro i processi aziendali.
          </div>
          <div data-reveal style={{ '--reveal-delay': '0.9s',
            marginTop: 'clamp(20px, 4vw, 36px)', display: 'flex', gap: 'clamp(12px, 3vw, 24px)', alignItems: 'center', flexWrap: 'wrap',
            fontFamily: rcTokens.mono, fontSize: 'clamp(9px, 2vw, 11px)', letterSpacing: 2, textTransform: 'uppercase',
          }}>
            <a href="#contact" className="rc-magnet" style={{
              background: rcTokens.ink, color: rcTokens.bg,
              padding: 'clamp(10px, 2vw, 14px) clamp(14px, 3vw, 22px)', textDecoration: 'none', letterSpacing: 2,
              whiteSpace: 'nowrap', fontSize: 'clamp(9px, 2vw, 11px)',
            }}>
              Contattami →
            </a>
            <a href="#what" className="rc-link" style={{ color: rcTokens.ink, textDecoration: 'none', paddingBottom: 2, whiteSpace: 'nowrap', fontSize: 'clamp(9px, 2vw, 11px)', display: 'flex', gap: '6px', alignItems: 'center' }}>
              <span style={{ animation: 'scrollBounce 2s ease-in-out infinite' }}>↓</span> Scorri per esplorare
            </a>
          </div>
        </div>

        {/* Terminale */}
        <div data-reveal="scale" style={{ '--reveal-delay': '1.1s', alignSelf: 'stretch', display: 'flex', alignItems: 'center', minHeight: '320px' }}>
          <div style={{
            width: '100%', border: `1px solid ${rcTokens.line}`, padding: '0 clamp(12px, 3vw, 22px)',
            background: isDark ? 'rgba(255,255,255,0.6)' : 'rgba(255,255,255,0.4)', backdropFilter: 'blur(4px)',
            overflowX: 'auto',
          }}>
            <Terminal started={started} theme={theme}/>
          </div>
        </div>
      </div>

      {/* Bottom strip: stats */}
      <div style={{
        marginTop: 'clamp(32px, 6vw, 48px)', borderTop: `1px solid ${rcTokens.line}`,
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
        fontFamily: rcTokens.mono,
      }}>
        {[
          { k: '20', suffix: '+', label: 'ANNI DI CODICE', count: true },
          { k: '5', suffix: '+', label: 'PIATTAFORME', count: true },
          { k: '∞', label: 'CAFFÈ' },
          { k: 'IT', label: 'BASED REMOTE' },
        ].map((s, i) => (
          <div key={i} data-reveal style={{ '--reveal-delay': (1.3 + i * 0.12) + 's',
            padding: 'clamp(12px, 3vw, 18px) 0', borderLeft: i > 0 ? `1px solid ${rcTokens.line}` : 'none', paddingLeft: i > 0 ? 'clamp(12px, 3vw, 20px)' : 0,
          }}>
            {s.count ? (
              <div style={{ fontSize: 'clamp(28px, 7vw, 36px)', fontFamily: rcTokens.serif, color: rcTokens.accent, fontWeight: 500, letterSpacing: -1 }}>
                <span data-count={s.k} data-count-suffix={s.suffix || ''}>0{s.suffix || ''}</span>
              </div>
            ) : (
              <div style={{ fontSize: 'clamp(28px, 7vw, 36px)', fontFamily: rcTokens.serif, color: rcTokens.accent, fontWeight: 500, letterSpacing: -1 }}>{s.k}</div>
            )}
            <div style={{ fontSize: 'clamp(8px, 2vw, 10px)', color: isDark ? rcTokens.inkDark : rcTokens.dim, marginTop: 'clamp(4px, 1vw, 2px)', letterSpacing: 2 }}>{s.label}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { TopNav, Loader, Hero });
