// ui_kits/portfolio/home.jsx
// HeroIntro split-panel cinematic reveal + existing editorial home.

const { useState, useEffect } = React;

// Module-level flag: play once per page load, reset on refresh
let _introPlayed = false;

// ============================================================
// useScramble — chars cycle randomly then settle on target
// ============================================================
function useScramble(target, duration, startDelay) {
  const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#@%&';
  const [text, setText] = useState(() =>
  target.split('').map((ch) => /[A-Z]/.test(ch) ? '·' : ch).join('')
  );
  useEffect(() => {
    let raf,startTime = null;
    const timeout = setTimeout(() => {
      const animate = (ts) => {
        if (!startTime) startTime = ts;
        const progress = Math.min((ts - startTime) / (duration || 900), 1);
        const result = target.split('').map((ch, i) => {
          if (!/[A-Z]/.test(ch)) return ch;
          const thr = i / Math.max(target.length - 1, 1) * 0.32;
          const cp = Math.max(0, (progress - thr) / (1 - thr + 0.001));
          if (cp >= 0.88) return ch;
          if (progress < 0.04) return '·';
          return CHARS[Math.floor(Math.random() * CHARS.length)];
        }).join('');
        setText(result);
        if (progress < 1) raf = requestAnimationFrame(animate);else
        setText(target);
      };
      raf = requestAnimationFrame(animate);
    }, startDelay || 120);
    return () => {clearTimeout(timeout);cancelAnimationFrame(raf);};
  }, []);
  return text;
}

// ============================================================
// IntroContent — logo + meta strip (rendered in both panels)
// ============================================================
function IntroContent({ logo, showMeta }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', pointerEvents: 'none' }}>
      {/* EL/ monogram */}
      <div style={{
        fontFamily: 'var(--ff-display)',
        fontSize: 'clamp(88px, 20vw, 300px)',
        fontWeight: 700,
        letterSpacing: '-0.055em',
        lineHeight: 1,
        userSelect: 'none'
      }}>
        {logo.split('').map((ch, i) =>
        <span key={i} style={{
          color: ch === '/' ? 'var(--accent)' : 'var(--fg-1)',
          display: 'inline-block',
          transition: 'color 120ms'
        }}>{ch}</span>
        )}
      </div>

      {/* Meta strip */}
      <div style={{
        display: 'flex',
        gap: 28,
        marginTop: 24,
        fontFamily: 'var(--ff-mono)',
        fontSize: 10,
        letterSpacing: '0.12em',
        textTransform: 'uppercase',
        color: 'rgba(242,240,235,0.22)',
        opacity: showMeta ? 1 : 0,
        transition: 'opacity 700ms ease',
        flexWrap: 'wrap',
        justifyContent: 'center',
        padding: '0 24px',
        textAlign: 'center'
      }}>
        <span>40.4168° N · 3.7038° W</span>
        <span style={{ color: 'rgba(242,240,235,0.08)' }}>×</span>
        <span>FULL-STACK · RED TEAM</span>
        <span style={{ color: 'rgba(242,240,235,0.08)' }}>×</span>
        <span>EST. 2019</span>
      </div>
    </div>);

}

// ============================================================
// IntroPanelInner — module-level so ref is stable across renders
// ============================================================
function IntroPanelInner({ anchorTop, logo, showMeta, glitch }) {
  return (
    <div style={{
      position: 'absolute',
      width: '100%',
      height: '100vh',
      top: anchorTop ? 0 : 'auto',
      bottom: anchorTop ? 'auto' : 0,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center'
    }}>
      {/* Glitch cyan/magenta offset layers */}
      {glitch &&
      <>
          <div style={{
          position: 'absolute',
          fontFamily: 'var(--ff-display)',
          fontSize: 'clamp(88px, 20vw, 300px)',
          fontWeight: 700,
          letterSpacing: '-0.055em',
          lineHeight: 1,
          color: 'var(--glitch-cyan)',
          opacity: 0.7,
          transform: 'translate(-3px, 0)',
          mixBlendMode: 'screen',
          userSelect: 'none',
          pointerEvents: 'none'
        }}>EL/</div>
          <div style={{
          position: 'absolute',
          fontFamily: 'var(--ff-display)',
          fontSize: 'clamp(88px, 20vw, 300px)',
          fontWeight: 700,
          letterSpacing: '-0.055em',
          lineHeight: 1,
          color: 'var(--glitch-magenta)',
          opacity: 0.7,
          transform: 'translate(3px, 0)',
          mixBlendMode: 'screen',
          userSelect: 'none',
          pointerEvents: 'none'
        }}>EL/</div>
        </>
      }
      <IntroContent logo={logo} showMeta={showMeta} />
    </div>);

}

// ============================================================
// HeroIntro — cinematic split-panel reveal
// ============================================================
function HeroIntro({ onDone }) {
  const [isSplit, setIsSplit] = useState(false);
  const [showMeta, setShowMeta] = useState(false);
  const [count, setCount] = useState(0);
  const [glitch, setGlitch] = useState(false);
  const logo = useScramble('EL/', 950, 120);

  useEffect(() => {
    // Count 0 → 100 over ~2.3s with ease-out curve
    let raf,t0 = null;
    const tick = (ts) => {
      if (!t0) t0 = ts;
      const p = Math.min((ts - t0) / 2300, 1);
      const ep = 1 - Math.pow(1 - p, 2.4);
      setCount(Math.round(ep * 100));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    const t1 = setTimeout(() => setShowMeta(true), 1100);
    const tg1 = setTimeout(() => setGlitch(true), 2300);
    const tg2 = setTimeout(() => setGlitch(false), 2420);
    const t2 = setTimeout(() => setIsSplit(true), 2500);
    const t3 = setTimeout(() => {_introPlayed = true;onDone();}, 3350);

    return () => {
      cancelAnimationFrame(raf);
      clearTimeout(t1);clearTimeout(tg1);clearTimeout(tg2);
      clearTimeout(t2);clearTimeout(t3);
    };
  }, []);

  const skip = () => {_introPlayed = true;onDone();};
  const TR = isSplit ? 'transform 850ms cubic-bezier(0.86, 0, 0.07, 1)' : 'none';

  return (
    <div
      onClick={skip}
      style={{ position: 'fixed', inset: 0, zIndex: 9997, cursor: 'pointer' }}>
      
      {/* ── Top panel ── */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
        background: 'var(--bg)', overflow: 'hidden',
        transform: isSplit ? 'translateY(-100%)' : 'none',
        transition: TR
      }}>
        <IntroPanelInner anchorTop={true} logo={logo} showMeta={showMeta} glitch={glitch} />
      </div>

      {/* ── Bottom panel ── */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: '50%',
        background: 'var(--bg)', overflow: 'hidden',
        transform: isSplit ? 'translateY(100%)' : 'none',
        transition: TR
      }}>
        <IntroPanelInner anchorTop={false} logo={logo} showMeta={showMeta} glitch={glitch} />
      </div>

      {/* ── Center hairline ── */}
      <div style={{
        position: 'absolute', top: '50%', left: 0, right: 0,
        height: '1px',
        background: glitch ?
        'rgba(58,107,255,0.6)' :
        'rgba(242,240,235,0.1)',
        transition: 'background 80ms',
        zIndex: 1, pointerEvents: 'none'
      }} />

      {/* ── Progress bar ── */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: '2px',
        background: 'rgba(242,240,235,0.05)', zIndex: 2, pointerEvents: 'none'
      }}>
        <div style={{
          height: '100%',
          width: count + '%',
          background: 'var(--accent)',
          transition: 'width 60ms linear'
        }} />
      </div>

      {/* ── Counter bottom-left ── */}
      <div style={{
        position: 'absolute', bottom: 22, left: 48, zIndex: 2, pointerEvents: 'none',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.14em',
        color: 'rgba(242,240,235,0.18)'
      }}>
        {String(count).padStart(3, '0')}
      </div>

      {/* ── Skip label ── */}
      <div style={{
        position: 'absolute', bottom: 22, right: 48, zIndex: 2, pointerEvents: 'none',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
        color: 'rgba(242,240,235,0.16)',
        opacity: showMeta ? 1 : 0,
        transition: 'opacity 500ms'
      }}>
        CLICK TO SKIP
      </div>

      {/* ── Version tag top-right ── */}
      <div style={{
        position: 'absolute', top: 22, right: 48, zIndex: 2, pointerEvents: 'none',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
        color: 'rgba(242,240,235,0.14)'
      }}>
        v07 · 2026
      </div>

      {/* ── Top-left label ── */}
      <div style={{
        position: 'absolute', top: 22, left: 48, zIndex: 2, pointerEvents: 'none',
        fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
        color: 'rgba(242,240,235,0.14)'
      }}>
        EDUARDO LÓPEZ
      </div>
    </div>);

}

// ============================================================
// HeroStatus — top status strip
// ============================================================
function HeroStatus({ lang }) {
  const t = useT(lang);
  return (
    <div className="hero-status">
      <div className="hero-status__item">
        <span className="hero-status__k">STATUS</span>
        <span className="hero-status__v"><span className="hero-status__dot" /> {t.status_available}</span>
      </div>
      <div className="hero-status__item">
        <span className="hero-status__k">LOCATION</span>
        <span className="hero-status__v">MADRID, ES - 40.4168° N · 3.7038° W</span>
      </div>
      <div className="hero-status__item">
        <span className="hero-status__k">FOCUS</span>
        <span className="hero-status__v">RED TEAM / FULL-STACK</span>
      </div>
    </div>);

}

// ============================================================
// FeaturedPost tile
// ============================================================
function FeaturedPost({ post, lang, go, index }) {
  const t = useT(lang);
  const num = String(index + 1).padStart(2, "0");
  return (
    <a href="#" data-cursor={t.home.readMore}
    onClick={(e) => {e.preventDefault();go("post", { slug: post.slug });}}
    className="featured-tile">
      {post.cover &&
      <div className="featured-tile__cover">
          <img src={post.cover} alt="" />
        </div>
      }
      <div className="featured-tile__meta">
        <span>{num}</span>
        <span>{formatDate(post.date, lang)}</span>
        <span className="featured-tile__cat">{post.category.toUpperCase()}</span>
      </div>
      <h3 className="feat-title">{tx(post.title, lang)}</h3>
      <p className="featured-tile__excerpt">{tx(post.excerpt, lang)}</p>
      <div className="featured-tile__cta">{t.home.readMore} <span className="arrow">→</span></div>
    </a>);

}

// ============================================================
// Home — Editorial with cinematic intro
// ============================================================
function Home({ lang, go }) {
  // Start visible if intro already played this page session
  const [introShown, setIntroShown] = useState(_introPlayed);
  const t = useT(lang);
  const featured = POSTS.filter((p) => p.featured).slice(0, 3);

  return (
    <div>
      {!introShown &&
      <HeroIntro onDone={() => setIntroShown(true)} />
      }

      {/* Content fades in after intro panels slide away */}
      <div style={{
        opacity: introShown ? 1 : 0,
        transform: introShown ? 'none' : 'translateY(8px)',
        transition: introShown ?
        'opacity 700ms cubic-bezier(0.2,0.7,0,1), transform 700ms cubic-bezier(0.2,0.7,0,1)' :
        'none'
      }}>
        <HeroStatus lang={lang} />

        <section className="hero">
          <div className="hero__year">EST. 2019 / Y07</div>
          <h1 className="hero__h1">
            <span className="hero__line hero__line--1">{t.home.hero1}</span>{" "}
            <em className="glitch hero__accent hero__line--2" data-text={t.home.heroAccent}>{t.home.heroAccent}</em>
            <br />
            <span className="hero__line hero__line--3">{t.home.hero2}</span>
          </h1>
          <Reveal delay={200}>
            <div className="hero__meta">
              <div className="hero__meta-col">
                <div className="hero__meta-lbl">— ROLE</div>
                <div className="hero__meta-val">Full-Stack Dev<br />Offensive Sec</div>
              </div>
              <div className="hero__meta-col">
                <div className="hero__meta-lbl">— BASED</div>
                <div className="hero__meta-val">Madrid · ES<br />Remote-friendly</div>
              </div>
              <div className="hero__meta-col">
                <div className="hero__meta-lbl">— SINCE</div>
                <div className="hero__meta-val">{POSTS.length} posts<br />2019 → now</div>
              </div>
            </div>
          </Reveal>
        </section>

        <Marquee items={t.status_marquee} />

        <section className="section">
          <Reveal>
            <header className="section__head">
              <div className="section__lbl">{t.home.featuredLabel}</div>
              <h2 className="section__title">{t.home.featuredTitle}</h2>
            </header>
          </Reveal>
          <div className="featured-grid">
            {featured.map((p, i) =>
            <Reveal key={p.id} delay={i * 120}>
                <FeaturedPost post={p} lang={lang} go={go} index={i} />
              </Reveal>
            )}
          </div>
        </section>

        <section className="section">
          <Reveal>
            <div className="all-row">
              <div className="section__lbl">{t.home.allWorkLabel}</div>
              <a href="#" data-cursor="open"
              onClick={(e) => {e.preventDefault();go("archive");}}
              className="see-all">
                {t.home.seeAll} <span className="arrow">→</span>
              </a>
            </div>
          </Reveal>
        </section>
      </div>
    </div>);

}

Object.assign(window, { Home, HeroStatus, FeaturedPost });