// Shared components: Nav, Footer, MotorcycleSVG, Mountains, utility icons
const { useState, useEffect, useRef, useMemo } = React;

function useT() {
  const lang = window.__lang || 'ro';
  return window.CONTENT[lang];
}

function Nav({ page, setPage, lang, setLang, goJoin }) {
  const t = window.CONTENT[lang];
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', on);
    return () => window.removeEventListener('scroll', on);
  }, []);
  const links = [
    { k: 'home', l: t.nav.home },
    { k: 'about', l: t.nav.about },
    { k: 'tours', l: t.nav.tours },
    { k: 'events', l: t.nav.events },
    { k: 'gallery', l: t.nav.gallery },
    { k: 'membership', l: t.nav.membership },
    { k: 'contact', l: t.nav.contact },
  ];
  const go = (k) => { setPage(k); setMobileOpen(false); };
  return (
    <>
    <nav className="nav" style={{ background: scrolled ? 'rgba(10,10,10,0.92)' : 'rgba(10,10,10,0.55)' }}>
      <div className="container nav-inner">
        <a className="nav-logo" onClick={() => go('home')} style={{ cursor: 'pointer' }}>
          <img src="/assets/logo.png" alt="Carpat Enduro Lupeni" />
          <div className="nav-logo-text">
            <span className="red">CARPAT</span>
            <span>ENDURO LUPENI</span>
            <span className="small">HARD ENDURO CREW</span>
          </div>
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.k} className={"nav-link " + (page === l.k ? 'active' : '')} onClick={() => go(l.k)}>{l.l}</a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-toggle">
            <button className={lang === 'ro' ? 'active' : ''} onClick={() => setLang('ro')}>RO</button>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <button className="btn-join" onClick={goJoin}>{t.cta_join} <span>→</span></button>
          <button className="nav-burger" onClick={() => setMobileOpen(m => !m)} aria-label="menu"><span></span></button>
        </div>
      </div>
    </nav>
    <div className={"mobile-menu " + (mobileOpen ? 'open' : '')}>
      {links.map(l => (
        <a key={l.k} className={"nav-link " + (page === l.k ? 'active' : '')} onClick={() => go(l.k)}>{l.l}</a>
      ))}
    </div>
    </>
  );
}

function Footer({ lang, setPage }) {
  const t = window.CONTENT[lang].footer;
  const nav = window.CONTENT[lang].nav;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">
              <img src="/assets/logo.png" alt="logo" />
              <div>
                <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontStyle: 'italic', fontSize: 22, lineHeight: 1, textTransform: 'uppercase' }}>
                  <span style={{ color: 'var(--accent)' }}>CARPAT</span> ENDURO
                </div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.18em', color: 'var(--fg-dim)', marginTop: 4 }}>STRAJA · LUPENI · HUNEDOARA, RO</div>
              </div>
            </div>
            <p style={{ color: 'var(--fg-dim)', maxWidth: 380, fontSize: 16, lineHeight: 1.6 }}>{t.tag}</p>
          </div>
          <div className="footer-col">
            <h4>{t.c_menu}</h4>
            <ul>
              {['home','about','tours','events','gallery','membership','contact'].map(k => (
                <li key={k}><a onClick={() => setPage(k)} style={{ cursor: 'pointer' }}>{nav[k]}</a></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.c_social}</h4>
            <ul>
              {window.SOCIALS.map(s => (
                <li key={s.k}><a href={s.url} target="_blank" rel="noopener">{s.k.charAt(0) + s.k.slice(1).toLowerCase()} ↗</a></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.c_contact}</h4>
            <ul>
              <li><a href={'mailto:' + window.CLUB_EMAIL}>{window.CLUB_EMAIL}</a></li>
              <li><a>Lupeni · Hunedoara, RO</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.copy}</span>
          <span className="footer-bottom-right">
            <a href="/admin" className="admin-link" onClick={e => { e.preventDefault(); setPage('admin'); }}>⚙ ADMIN</a>
            <span>{t.built}</span>
          </span>
        </div>
      </div>
    </footer>
  );
}

// Enduro motorcycle SVG — clean silhouette, wheels spin with SVG animateTransform (rock solid).
function MotorcycleSVG({ color = '#fff', wheelColor = '#dc2626', accent = '#dc2626' }) {
  // viewBox 0 0 320 160.
  const BACK_CX = 70, FRONT_CX = 258, CY = 118, R = 36;

  // A wheel centered at (0,0). Parent <g> translates it into place.
  const Wheel = () => (
    <g>
      {/* tire */}
      <circle cx="0" cy="0" r={R} fill="#0a0a0a" stroke={color} strokeWidth="2" />
      {/* knobby tread ticks */}
      <g stroke={color} strokeWidth="1.5" opacity="0.55">
        {[...Array(16)].map((_, i) => {
          const a = (i / 16) * 360;
          return (
            <line key={i} x1="0" y1={-(R - 3)} x2="0" y2={-R} transform={`rotate(${a})`} />
          );
        })}
      </g>
      {/* rotating rim + spokes — animateTransform is SMIL, doesn't care about transform-box */}
      <g>
        <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="0.55s" repeatCount="indefinite" />
        <circle cx="0" cy="0" r="26" fill="none" stroke={color} strokeWidth="2" />
        <circle cx="0" cy="0" r="7" fill={wheelColor} stroke={color} strokeWidth="1.5" />
        {[...Array(6)].map((_, i) => {
          const a = (i / 6) * 360;
          return (
            <line key={i} x1="0" y1="0" x2="0" y2={-25} stroke={color} strokeWidth="1.3" transform={`rotate(${a})`} />
          );
        })}
      </g>
    </g>
  );

  return (
    <svg viewBox="0 0 320 160" width="100%" height="100%" style={{ overflow: 'visible' }} preserveAspectRatio="xMidYMid meet">
      {/* Shadow */}
      <ellipse cx="160" cy="152" rx="125" ry="4" fill="#000" opacity="0.55" />

      {/* BACK WHEEL */}
      <g transform={`translate(${BACK_CX} ${CY})`}><Wheel /></g>

      {/* Rear shock + swingarm */}
      <path d="M 70 118 L 125 95" stroke={color} strokeWidth="5" strokeLinecap="round" />
      <rect x="115" y="68" width="6" height="30" fill={wheelColor} rx="1" transform="rotate(-12 118 82)" />

      {/* Rear fender / mudguard (high enduro style) */}
      <path d="M 40 95 Q 70 75, 118 82 L 130 78 L 134 86 L 122 92 Q 90 82, 48 102 Z" fill="#1a1a1a" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />

      {/* Side number plate */}
      <g>
        <path d="M 34 68 L 66 62 L 72 92 L 40 98 Z" fill="#fff" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
        <text x="53" y="86" fontFamily="Barlow Condensed, sans-serif" fontWeight="900" fontStyle="italic" fontSize="22" fill="#0a0a0a" textAnchor="middle">47</text>
      </g>

      {/* Seat */}
      <path d="M 90 62 Q 130 50, 180 52 L 190 60 L 180 66 Q 140 64, 96 72 Z" fill="#0a0a0a" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
      <path d="M 98 66 Q 140 58, 184 60" stroke={color} strokeWidth="0.8" fill="none" opacity="0.4" strokeDasharray="2 2" />

      {/* Fuel tank */}
      <path d="M 138 52 Q 165 38, 210 42 L 218 60 Q 205 68, 168 72 Q 146 70, 138 60 Z" fill={wheelColor} stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
      <path d="M 152 54 L 210 48 L 212 54 L 154 60 Z" fill="#0a0a0a" opacity="0.9" />

      {/* Engine block + cylinder */}
      <g>
        <path d="M 140 82 L 200 82 L 208 118 L 150 118 Z" fill="#0a0a0a" stroke={color} strokeWidth="1.8" strokeLinejoin="round" />
        {[...Array(5)].map((_, i) => (
          <line key={i} x1={155 + i * 8} y1="88" x2={155 + i * 8} y2="112" stroke={color} strokeWidth="0.8" opacity="0.4" />
        ))}
        <rect x="162" y="62" width="24" height="22" fill="#0a0a0a" stroke={color} strokeWidth="1.5" />
        {[...Array(4)].map((_, i) => (
          <line key={i} x1="164" y1={66 + i * 5} x2="184" y2={66 + i * 5} stroke={color} strokeWidth="0.8" opacity="0.5" />
        ))}
      </g>

      {/* Frame rails */}
      <path d="M 125 72 L 160 52" stroke={color} strokeWidth="3" fill="none" strokeLinecap="round" />
      <path d="M 210 60 L 230 78" stroke={color} strokeWidth="3" fill="none" strokeLinecap="round" />
      <path d="M 216 80 L 232 110" stroke={color} strokeWidth="2.5" fill="none" strokeLinecap="round" />

      {/* Front fork (inverted) */}
      <path d="M 235 58 L 252 110" stroke={color} strokeWidth="4" fill="none" strokeLinecap="round" />
      <path d="M 245 62 L 260 112" stroke="#0a0a0a" strokeWidth="3" fill="none" strokeLinecap="round" />

      {/* Front fender */}
      <path d="M 228 92 Q 258 84, 286 96 L 284 102 Q 258 92, 232 100 Z" fill="#1a1a1a" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />

      {/* Handlebar */}
      <path d="M 212 46 L 240 34 L 258 34" stroke={color} strokeWidth="3.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="258" cy="34" r="3" fill={color} />
      <rect x="226" y="30" width="18" height="5" fill="#0a0a0a" stroke={color} strokeWidth="1" rx="1" />
      {/* Headlight */}
      <path d="M 248 42 L 268 38 L 270 54 L 252 58 Z" fill="#fff" stroke={color} strokeWidth="1.5" strokeLinejoin="round" opacity="0.95" />
      <ellipse cx="260" cy="48" rx="4" ry="5" fill={accent} opacity="0.8" />

      {/* Exhaust */}
      <path d="M 205 100 Q 230 108, 255 102 L 258 106 Q 232 112, 204 106 Z" fill="#0a0a0a" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
      <circle cx="256" cy="104" r="2" fill={accent} opacity="0.6" />

      {/* FRONT WHEEL */}
      <g transform={`translate(${FRONT_CX} ${CY})`}><Wheel /></g>
    </svg>
  );
}

// Layered mountain silhouette with parallax
function Mountains({ scrollY = 0 }) {
  return (
    <svg viewBox="0 0 1920 500" preserveAspectRatio="xMidYMax slice"
      style={{ position: 'absolute', bottom: 0, left: 0, width: '100%', height: '60%', pointerEvents: 'none' }}>
      <defs>
        <linearGradient id="mt1" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#1a1a1a" />
          <stop offset="100%" stopColor="#0a0a0a" />
        </linearGradient>
        <linearGradient id="mt2" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#2a0505" />
          <stop offset="100%" stopColor="#0a0a0a" />
        </linearGradient>
      </defs>
      {/* back mountains */}
      <g style={{ transform: `translateY(${scrollY * 0.05}px)` }}>
        <path d="M 0 400 L 180 180 L 320 280 L 500 120 L 680 240 L 880 100 L 1060 220 L 1240 140 L 1440 280 L 1620 160 L 1800 260 L 1920 200 L 1920 500 L 0 500 Z" fill="url(#mt2)" opacity="0.8" />
      </g>
      {/* mid mountains */}
      <g style={{ transform: `translateY(${scrollY * 0.12}px)` }}>
        <path d="M 0 450 L 120 300 L 280 380 L 460 220 L 620 340 L 820 180 L 1000 320 L 1180 200 L 1380 360 L 1560 240 L 1780 340 L 1920 280 L 1920 500 L 0 500 Z" fill="url(#mt1)" />
      </g>
      {/* front ridge with snow caps (red accents like logo) */}
      <g style={{ transform: `translateY(${scrollY * 0.2}px)` }}>
        <path d="M 0 500 L 90 400 L 180 440 L 300 360 L 420 420 L 560 320 L 700 400 L 840 340 L 980 420 L 1120 340 L 1280 420 L 1440 360 L 1600 420 L 1760 380 L 1920 430 L 1920 500 Z" fill="#0a0a0a" />
        {/* small red peak accents like the logo */}
        <path d="M 556 320 L 568 344 L 564 340 L 556 350 L 550 340 Z" fill="#dc2626" />
        <path d="M 836 340 L 848 360 L 842 358 L 836 368 L 828 356 Z" fill="#dc2626" />
      </g>
    </svg>
  );
}

function DiffBadge({ d }) {
  const colors = {
    EASY: { bg: '#143d2a', fg: '#6ee7b7', border: '#1f6b4a' },
    MID:  { bg: '#3b2e10', fg: '#fcd34d', border: '#6b5118' },
    HARD: { bg: '#3b0d0d', fg: '#ef3b3b', border: '#7f1313' },
  }[d] || { bg: '#222', fg: '#fff', border: '#333' };
  return (
    <span style={{
      fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
      padding: '4px 10px', letterSpacing: '0.12em',
      color: colors.fg, background: colors.bg, border: '1px solid ' + colors.border,
    }}>{d}</span>
  );
}

// Photo placeholder with striped monospace overlay (our style guide)
function PlaceholderPhoto({ hue = 0, label = 'PHOTO', height = 240, count }) {
  const bg = `hsl(${hue}, 10%, 12%)`;
  const stripe = `hsl(${hue}, 15%, 18%)`;
  return (
    <div style={{
      position: 'relative', width: '100%', height,
      background: `repeating-linear-gradient(135deg, ${bg} 0 20px, ${stripe} 20px 21px)`,
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-start',
        padding: 16,
      }}>
        <div>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.2em', color: 'rgba(255,255,255,0.45)', marginBottom: 4 }}>
            [ PLACEHOLDER ]
          </div>
          <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontStyle: 'italic', fontSize: 18, textTransform: 'uppercase', color: 'rgba(255,255,255,0.75)' }}>
            {label}
          </div>
        </div>
      </div>
      {count && (
        <div style={{
          position: 'absolute', top: 12, right: 12,
          fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
          background: 'rgba(0,0,0,0.6)', color: '#fff',
          padding: '4px 8px', letterSpacing: '0.08em',
        }}>{count}</div>
      )}
    </div>
  );
}

// Moving ticker
function Ticker({ items }) {
  return (
    <div style={{
      background: 'var(--accent)', color: '#fff', padding: '14px 0',
      overflow: 'hidden', position: 'relative',
      fontFamily: 'Barlow Condensed', fontStyle: 'italic', fontWeight: 900,
      textTransform: 'uppercase', fontSize: 20, letterSpacing: '0.02em',
    }}>
      <div style={{ display: 'inline-flex', gap: 40, whiteSpace: 'nowrap', animation: 'tickerScroll 30s linear infinite' }}>
        {[...items, ...items, ...items].map((it, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 40 }}>
            {it}
            <span style={{ fontSize: 14, opacity: 0.7 }}>✦</span>
          </span>
        ))}
      </div>
      <style>{`@keyframes tickerScroll { from { transform: translateX(0); } to { transform: translateX(-33.33%); } }`}</style>
    </div>
  );
}

// Success popup — brand-styled confirmation modal
function SuccessModal({ open, onClose, title, body, cta }) {
  if (!open) return null;
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.82)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} className="fade-up torn" style={{
        maxWidth: 560, width: '100%', background: 'var(--bg-2)',
        border: '1px solid var(--border-bright)', position: 'relative',
        padding: '52px 44px 44px', textAlign: 'center', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: 'var(--accent)' }}></div>
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.5,
          background: 'radial-gradient(600px 300px at 50% -80px, rgba(220,38,38,0.15), transparent 70%)',
        }}></div>
        <button onClick={onClose} aria-label="close" style={{ position: 'absolute', top: 14, right: 16, fontSize: 22, color: 'var(--fg-dim)', padding: 6 }}>✕</button>

        <div style={{
          width: 76, height: 76, margin: '0 auto 26px', background: 'var(--accent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          clipPath: 'polygon(0 0, calc(100% - 14px) 0, 100% 14px, 100% 100%, 14px 100%, 0 calc(100% - 14px))',
          boxShadow: '0 0 50px rgba(220,38,38,0.45)',
        }}>
          <svg width="38" height="38" viewBox="0 0 24 24" fill="none">
            <path d="M4 12.5 L9.5 18 L20 6.5" stroke="#fff" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>

        <div className="display" style={{ fontSize: 'clamp(30px, 5vw, 42px)', lineHeight: 1.05, marginBottom: 16 }}>{title}</div>
        <p style={{ color: 'var(--fg-dim)', fontSize: 16.5, lineHeight: 1.6, maxWidth: 420, margin: '0 auto 32px' }}>{body}</p>
        <button className="btn btn-primary" onClick={onClose} style={{ justifyContent: 'center', minWidth: 180 }}>
          {cta} <span className="arrow">→</span>
        </button>
        <div className="mono" style={{ marginTop: 26, fontSize: 10, letterSpacing: '0.22em', color: 'var(--fg-dimmer)' }}>
          CARPAT ENDURO LUPENI · ÎMPREUNĂ PENTRU PASIUNE, RESPECT ȘI PERFORMANȚĂ
        </div>
      </div>
    </div>,
    document.body
  );
}

// Section heading block
function SectionHead({ eyebrow, titleLines, right }) {
  return (
    <div className="section-head">
      <div>
        <div className="eyebrow" style={{ marginBottom: 18 }}>{eyebrow}</div>
        <h2 className="display display-lg">
          {titleLines.map((l, i) => (
            <div key={i} style={i === titleLines.length - 1 ? { color: 'var(--accent)' } : {}}>{l}</div>
          ))}
        </h2>
      </div>
      {right}
    </div>
  );
}

Object.assign(window, { Nav, Footer, MotorcycleSVG, Mountains, DiffBadge, PlaceholderPhoto, Ticker, SectionHead, SuccessModal, useT });
