// Hi-fi shared primitives — Evveland Direction A
const { useState, useEffect, useRef } = React;

function LogoMark({ size = 32 }) {
  // Isometric hexagon wireframe with nodes — redrawn in gold/violet palette.
  // Hex is drawn with lines connecting 6 outer vertices + a center node; gold primary, violet secondary.
  return (
    <span className="logo-mark" style={{ width: size, height: size }}>
      <svg viewBox="0 0 48 48" width={size} height={size} style={{ overflow: 'visible' }}>
        <defs>
          <linearGradient id="evv-stroke" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#FFE38A"/>
            <stop offset="55%" stopColor="#FFC93C"/>
            <stop offset="100%" stopColor="#7C5CFF"/>
          </linearGradient>
          <radialGradient id="evv-node" cx="0.5" cy="0.4">
            <stop offset="0%" stopColor="#FFF5C9"/>
            <stop offset="60%" stopColor="#FFC93C"/>
            <stop offset="100%" stopColor="#FFB800"/>
          </radialGradient>
        </defs>
        {/* Hexagon edges */}
        <polygon
          points="24,4 42,14 42,34 24,44 6,34 6,14"
          fill="none"
          stroke="url(#evv-stroke)"
          strokeWidth="2.2"
          strokeLinejoin="round"
        />
        {/* Internal "Y" linking to center */}
        <path
          d="M24 24 L24 4 M24 24 L42 34 M24 24 L6 34"
          fill="none"
          stroke="url(#evv-stroke)"
          strokeWidth="2.2"
          strokeLinecap="round"
          strokeLinejoin="round"
          opacity="0.85"
        />
        {/* Nodes */}
        {[[24,4],[42,14],[42,34],[24,44],[6,34],[6,14],[24,24]].map(([cx,cy],i) => (
          <circle key={i} cx={cx} cy={cy} r={i === 6 ? 2.6 : 2.2} fill="url(#evv-node)" stroke="#111" strokeWidth="0.6"/>
        ))}
      </svg>
    </span>
  );
}

function Wordmark({ height = 22 }) {
  // Stencil-style wordmark "EVVELAND" — gold→violet gradient, consistent E and closing bracket D
  const w = height * 7.2;
  return (
    <svg viewBox="0 0 360 50" height={height} width={w} style={{ display: 'block' }}>
      <defs>
        <linearGradient id="evv-word" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#FFE38A"/>
          <stop offset="50%" stopColor="#FFC93C"/>
          <stop offset="100%" stopColor="#7C5CFF"/>
        </linearGradient>
      </defs>
      <text
        x="0" y="40"
        fontFamily="Space Grotesk, sans-serif"
        fontWeight="700"
        fontSize="46"
        letterSpacing="2"
        fill="url(#evv-word)"
      >EVVELAND</text>
    </svg>
  );
}

function Logo({ onClick }) {
  return (
    <a className="logo" href="#" onClick={(e) => { e.preventDefault(); onClick && onClick(); }} style={{ gap: 12 }}>
      <LogoMark size={34}/>
      <Wordmark height={20}/>
    </a>
  );
}

function Nav({ page, setPage }) {
  const t = useT();
  const links = [
    ['home', 'nav.home'],
    ['create', 'nav.create'],
    ['work', 'nav.work'],
    ['services', 'nav.services'],
    ['contact', 'nav.contact'],
    ['blog', 'nav.blog'],
  ];
  const [mobileOpen, setMobileOpen] = useState(false);

  // Lock scroll while mobile drawer is open
  useEffect(() => {
    if (mobileOpen) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [mobileOpen]);

  // Close drawer when page changes
  useEffect(() => { setMobileOpen(false); }, [page]);

  return (
    <nav className="nav">
      <div className="nav-inner">
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          <Logo onClick={() => setPage('home')}/>
          <span className="tag nav-tag" style={{ background: 'rgba(255,201,60,0.08)', color: 'var(--accent)', borderColor: 'rgba(255,201,60,0.3)' }}>{t('nav.tag')}</span>
        </div>
        <div className="nav-links">
          {links.map(([key, tk]) => (
            <button key={key} className={`nav-link ${page === key ? 'active' : ''}`} onClick={() => setPage(key)}>
              {t(tk)}
              {key === 'create' && <span style={{ marginLeft: 6, fontSize: 9, padding: '2px 5px', borderRadius: 3, background: 'rgba(255,40,220,0.18)', color: '#FF28DC', letterSpacing: '0.1em', fontFamily: 'JetBrains Mono', fontWeight: 600, verticalAlign: '2px' }}>{t('nav.beta')}</span>}
            </button>
          ))}
        </div>
        <div className="nav-cta" style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <LangToggle/>
          <a className="btn btn-primary nav-book" href="https://calendly.com/evveland" target="_blank" rel="noopener">{t('nav.book')} <span className="chev">→</span></a>
          <button
            className={`nav-burger ${mobileOpen ? 'open' : ''}`}
            aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={mobileOpen}
            onClick={() => setMobileOpen(!mobileOpen)}
          >
            <span/><span/><span/>
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      <div className={`nav-mobile ${mobileOpen ? 'open' : ''}`} role="dialog" aria-modal="true" aria-hidden={!mobileOpen}>
        <div className="nav-mobile-inner">
          <ul className="nav-mobile-links">
            {links.map(([key, tk]) => (
              <li key={key}>
                <button
                  className={`nav-mobile-link ${page === key ? 'active' : ''}`}
                  onClick={() => { setPage(key); setMobileOpen(false); }}
                >
                  <span>{t(tk)}</span>
                  <span className="chev">→</span>
                </button>
              </li>
            ))}
          </ul>
          <a className="btn btn-primary btn-lg" href="https://calendly.com/evveland" target="_blank" rel="noopener" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>{t('nav.book')} <span className="chev">→</span></a>
          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}>
            <LangToggle size="md"/>
          </div>
          <div className="nav-mobile-social">
            <a href="https://t.me/evveland" target="_blank" rel="noopener">Telegram</a>
            <a href="https://x.com/evveland_web3" target="_blank" rel="noopener">X / Twitter</a>
            <a href="https://www.linkedin.com/company/evveland/" target="_blank" rel="noopener">LinkedIn</a>
          </div>
        </div>
      </div>
    </nav>
  );
}

// Breadcrumbs — shown at top of internal pages
const PAGE_TITLES = {
  home: 'Home', create: 'GrowthPad', work: 'Work', services: 'Services',
  about: 'About', contact: 'Contact', blog: 'Blog', post: 'Post',
};
function Breadcrumbs({ setPage, items = [], current }) {
  const t = useT();
  // items: optional array of [label, pageKey] for intermediate crumbs (e.g. Blog → Post)
  return (
    <nav className="breadcrumbs" aria-label="Breadcrumb">
      <div className="wrap">
        <ol className="crumbs">
          <li>
            <a href="#" onClick={(e) => { e.preventDefault(); setPage('home'); }}>
              <svg width="13" height="13" viewBox="0 0 16 16" fill="none" style={{ marginRight: 6, verticalAlign: '-2px' }}>
                <path d="M2 7L8 2L14 7V13.5C14 13.776 13.776 14 13.5 14H10V10H6V14H2.5C2.224 14 2 13.776 2 13.5V7Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
              </svg>
              {t('crumb.home')}
            </a>
          </li>
          {items.map(([label, key], i) => (
            <li key={i}>
              <span className="crumb-sep" aria-hidden="true">/</span>
              <a href="#" onClick={(e) => { e.preventDefault(); setPage(key); }}>{label}</a>
            </li>
          ))}
          <li aria-current="page">
            <span className="crumb-sep" aria-hidden="true">/</span>
            <span className="crumb-current">{current}</span>
          </li>
        </ol>
      </div>
    </nav>
  );
}

// Cartridge card
function Cartridge({ color = 'var(--accent)', tag, tagClass = 'tag', title, subtitle, meta = [], screen, href, compact }) {
  return (
    <div className="cart" style={{ '--cart-color': color }}>
      <div className="cart-body">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span className="cart-label">MINIAPP /{meta[0] || 'live'}</span>
          <span className={tagClass}>{tag}</span>
        </div>
        {screen}
        <div style={{ marginTop: 20 }}>
          <h3 className="display" style={{ fontSize: compact ? 22 : 28, letterSpacing: '-0.02em' }}>{title}</h3>
          <div style={{ color: 'var(--text-3)', fontSize: 14, marginTop: 4 }}>{subtitle}</div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {meta.slice(1).map((m) => <span key={m} className="mono" style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{m}</span>).reduce((acc, el, i) => i === 0 ? [el] : [...acc, <span key={`s${i}`} style={{ color: 'var(--text-4)' }}>·</span>, el], [])}
          </div>
          <a href={href || '#'} style={{ color: color, fontSize: 13, fontWeight: 600, textDecoration: 'none', fontFamily: 'JetBrains Mono, monospace' }}>OPEN →</a>
        </div>
      </div>
    </div>
  );
}

// Miniapp phone screen — real screenshot inside phone frame
function PhoneShot({ src, alt }) {
  return (
    <div className="phone-hifi" style={{ width: '100%', aspectRatio: '804/1388' }}>
      <div className="phone-screen-hifi">
        <img src={src} alt={alt} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'top', display: 'block' }}/>
      </div>
    </div>
  );
}

function IncaverseScreen() { return <PhoneShot src="assets/incaverse.png" alt="Incaverse: Rise of the Tribes"/>; }
function IncaverseHeroScreen() { return <PhoneShot src="assets/incaverse-hero.png" alt="Incaverse: Tupaq Illapa"/>; }
function ChipsyScreen() { return <PhoneShot src="assets/chipsy.png" alt="Chipsy"/>; }
function PlumpScreen() { return <PhoneShot src="assets/plump.png" alt="Plump"/>; }

function SpinScreen() {
  return (
    <div className="phone-hifi" style={{ width: '100%', aspectRatio: '9/13' }}>
      <div className="phone-notch"/>
      <div className="phone-screen-hifi">
        <div style={{ height: '100%', background: 'linear-gradient(180deg, #151229 0%, #0c0e15 70%)', padding: '28px 12px 10px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <div style={{ fontFamily: 'Space Grotesk', fontSize: 11, fontWeight: 700, color: '#7C5CFF', textAlign: 'center' }}>SPIN THE WHEEL</div>
          <div style={{ fontSize: 7, color: '#7B819A', textAlign: 'center', fontFamily: 'JetBrains Mono', letterSpacing: '0.15em' }}>COMING SOON</div>
          <div style={{ margin: '12px auto', width: 80, height: 80, borderRadius: '50%', background: 'conic-gradient(#FFC93C 0 20%, #7C5CFF 20% 40%, #24E1A4 40% 60%, #FF5CA8 60% 80%, #5E3DFF 80% 100%)', position: 'relative', border: '2px solid #1F2432' }}>
            <div style={{ position: 'absolute', top: -6, left: '50%', transform: 'translateX(-50%)', width: 0, height: 0, borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTop: '8px solid #fff' }}/>
            <div style={{ position: 'absolute', inset: '35%', borderRadius: '50%', background: '#0c0e15', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 10 }}>SPIN</div>
          </div>
          <div style={{ marginTop: 'auto', background: '#7C5CFF', color: '#0c0e15', borderRadius: 8, padding: '6px', textAlign: 'center', fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 11, width: '100%' }}>NOTIFY ME</div>
        </div>
      </div>
    </div>
  );
}

function Metric({ num, label, sub, gold }) {
  return (
    <div>
      <div className={`metric-num ${gold ? 'gold' : ''}`}>{num}</div>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--text-3)', marginTop: 12 }}>{label}</div>
      {sub && <div style={{ fontSize: 14, color: 'var(--text-2)', marginTop: 8, maxWidth: 240 }}>{sub}</div>}
    </div>
  );
}

function Ticker({ items }) {
  const row = items.map((t, i) => (
    <span key={i} className="ticker-item"><span>{t}</span><span className="sep"/></span>
  ));
  return (
    <div className="ticker">
      <div className="ticker-track">{row}{row}{row}</div>
    </div>
  );
}

function Reveal({ children, delay = 0, style, className = '' }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let done = false;
    const markIn = () => { if (!done) { done = true; el.classList.add('in'); } };
    // Always schedule a guaranteed reveal after delay + 500ms
    const fallback = setTimeout(markIn, delay + 500);
    // Also try IntersectionObserver for a nicer staggered effect when scrolled into view
    try {
      const io = new IntersectionObserver(([e]) => {
        if (e.isIntersecting) {
          setTimeout(markIn, delay);
          io.disconnect();
        }
      }, { threshold: 0.05 });
      io.observe(el);
      return () => { io.disconnect(); clearTimeout(fallback); };
    } catch (e) {
      return () => clearTimeout(fallback);
    }
  }, [delay]);
  return <div ref={ref} className={`reveal ${className}`} style={style}>{children}</div>;
}

function Footer({ setPage }) {
  const t = useT();
  const siteLinks = [
    ['home', 'nav.home'],
    ['create', 'nav.create'],
    ['work', 'nav.work'],
    ['services', 'nav.services'],
    ['about', 'nav.about'],
    ['contact', 'nav.contact'],
    ['blog', 'nav.blog'],
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Logo onClick={() => setPage('home')}/>
            <p style={{ color: 'var(--text-3)', fontSize: 14, marginTop: 16, maxWidth: 320 }}>
              {t('footer.tagline')}
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
              <a href="https://t.me/evveland" target="_blank" rel="noopener" className="tag" style={{ cursor: 'pointer' }}>t.me/evveland</a>
              <a href="https://x.com/evveland_web3" target="_blank" rel="noopener" className="tag" style={{ cursor: 'pointer' }}>x.com/evveland_web3</a>
              <a href="https://www.linkedin.com/company/evveland/" target="_blank" rel="noopener" className="tag" style={{ cursor: 'pointer' }}>linkedin.com/company/evveland</a>
            </div>
          </div>
          <div>
            <h5>{t('footer.site')}</h5>
            <ul>
              {siteLinks.map(([key, tk]) => (
                <li key={key}><a href="#" onClick={(e) => { e.preventDefault(); setPage(key); }}>{t(tk)}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>{t('footer.live')}</h5>
            <ul>
              <li><a href="#">Incaverse S3 · Rise of the Tribes (soon) →</a></li>
              <li><a href="https://t.me/incaverse_bot" target="_blank" rel="noopener">Incaverse S2 · Chinchaysuyu →</a></li>
              <li><a href="https://t.me/incaverse2d_bot" target="_blank" rel="noopener">Incaverse S1 · Tap2Earn →</a></li>
              <li><a href="https://t.me/chipsycasino_bot/play" target="_blank" rel="noopener">Chipsy →</a></li>
              <li><a href="https://t.me/plumpcasino_bot/play" target="_blank" rel="noopener">Plump →</a></li>
            </ul>
          </div>
          <div>
            <h5>{t('footer.contactCol')}</h5>
            <ul>
              <li><a href="mailto:info@evveland.com">CONTACT</a></li>
              <li><a href="https://t.me/evveland" target="_blank" rel="noopener">t.me/evveland</a></li>
            </ul>
            <div style={{ marginTop: 16 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-4)', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 8 }}>{t('footer.lang')}</div>
              <LangToggle/>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-4)' }}>© 2026 EVVELAND · ALL RIGHTS RESERVED</span>
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-4)' }}>BUILDING IN TELEGRAM</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Logo, LogoMark, Nav, Breadcrumbs, Cartridge, Metric, Ticker, Reveal, Footer,
  IncaverseScreen, IncaverseHeroScreen, ChipsyScreen, PlumpScreen, SpinScreen,
});
