/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

// ====== SHARED COMPONENTS ======
function BrandMark({ size = 38, color, copperColor }) {
  const navy = color || "var(--navy-700)";
  const copper = copperColor || "var(--accent)";
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" fill="none" aria-label="Port & Terminal Services Spain">
      <line x1="6" y1="34" x2="54" y2="34" stroke={navy} strokeWidth="1.6" strokeLinecap="square" />
      <path d="M28 34 L28 14 L42 24 L42 34" stroke={navy} strokeWidth="1.6" fill="none" strokeLinejoin="miter" />
      <line x1="42" y1="14" x2="48" y2="14" stroke={navy} strokeWidth="1.6" />
      <line x1="14" y1="38" x2="34" y2="38" stroke={navy} strokeWidth="1.2" />
      <line x1="20" y1="42" x2="38" y2="42" stroke={navy} strokeWidth="1.2" />
      <line x1="26" y1="46" x2="44" y2="46" stroke={navy} strokeWidth="1.2" />
      <line x1="22" y1="50" x2="36" y2="50" stroke={copper} strokeWidth="1.2" />
    </svg>
  );
}

function Header({ active = "home", t, lang, setLang, transparent = false }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header className={`site-header ${transparent ? "transparent" : ""} ${scrolled ? "scrolled" : ""}`}>
      <div className="container header-inner">
        <a href="home.html" className="brand" aria-label="Port & Terminal Services Spain">
          <BrandMark size={38} color={transparent && !scrolled ? "white" : undefined} copperColor={transparent && !scrolled ? "var(--copper-500)" : undefined} />
          <span className="brand-text">
            <span className="pt">PORT &amp; TERMINAL</span>
            <span className="ss">Services Spain</span>
          </span>
        </a>
        <nav className="nav">
          <a href="services.html" className={active === "services" ? "active" : ""}>{t.nav.services}</a>
          <a href="ports.html" className={active === "ports" ? "active" : ""}>{t.nav.ports}</a>
          <a href="about.html" className={active === "about" ? "active" : ""}>{t.nav.about}</a>
          <a href="sustainability.html" className={active === "sustain" ? "active" : ""}>{t.nav.sustain}</a>
          <a href="news.html" className={active === "news" ? "active" : ""}>{t.nav.news}</a>
          <a href="contact.html" className={active === "contact" ? "active" : ""}>{t.nav.contact}</a>
        </nav>
        <div className="header-actions">
          <div className="lang-switch" role="group" aria-label="Language">
            <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
            <span className="sep">/</span>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a href="contact.html" className="btn">
            {t.cta.quote}
            <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </header>
  );
}

function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div>
            <BrandMark size={48} color="white" copperColor="var(--copper-500)" />
            <div className="footer-brand" style={{ marginTop: 24 }}>{t.footer.tagline}</div>
          </div>
          <div className="footer-col">
            <h4>{t.footer.col1}</h4>
            <ul>
              {t.services.map(s => <li key={s.id}><a href={`services.html#${s.id}`}>{s.name}</a></li>)}
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.footer.col2}</h4>
            <ul>
              <li><a href="about.html">{t.nav.about}</a></li>
              <li><a href="sustainability.html">{t.nav.sustain}</a></li>
              <li><a href="news.html">{t.nav.news}</a></li>
              <li><a href="ports.html">{t.nav.ports}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.footer.col3}</h4>
            <ul>
              {t.footer.contact_lines.map((l, i) => <li key={i}>{l}</li>)}
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.copy}</span>
          <span><a href="#">{t.footer.legal}</a></span>
        </div>
      </div>
    </footer>
  );
}

// ====== HOOKS ======
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));

    // Stats section — trigger count-up animation when visible
    const stats = document.querySelectorAll(".stats");
    const statsIo = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in-view"); statsIo.unobserve(e.target); } });
    }, { threshold: 0.3 });
    stats.forEach(el => statsIo.observe(el));

    // Subtle parallax for hero media
    const heroMedia = document.querySelector(".hero-media");
    let ticking = false;
    const onScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          const y = window.scrollY;
          if (heroMedia && y < window.innerHeight) {
            heroMedia.style.transform = `translateY(${y * 0.25}px)`;
          }
          ticking = false;
        });
        ticking = true;
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      io.disconnect();
      statsIo.disconnect();
      window.removeEventListener("scroll", onScroll);
    };
  }, []);
}

function useLang() {
  const [lang, setLangState] = useState(window.PT_LANG);
  useEffect(() => {
    const onChange = (e) => setLangState(e.detail);
    window.addEventListener("pt-lang-change", onChange);
    return () => window.removeEventListener("pt-lang-change", onChange);
  }, []);
  const setLang = (l) => window.setPTLang(l);
  return [lang, setLang, window.PT_CONTENT[lang]];
}

// ====== EDITORIAL FIGURE PLACEHOLDER ======
function Figure({ label, caption, className = "", tone = "navy" }) {
  return (
    <div className={`figure ${className}`}>
      <div className="figure-stripe" />
      <div className="figure-label">{label}</div>
      {caption && <div className="figure-caption">{caption}</div>}
    </div>
  );
}

// ====== SPAIN MAP ======
function SpainMap({ ports }) {
  // Approximate normalized coordinates for Spanish ports on a stylized map
  const pins = [
    { code: "BCN", name: "Barcelona", x: 760, y: 220, major: true },
    { code: "VLC", name: "Valencia", x: 660, y: 320, major: true },
    { code: "ALG", name: "Algeciras", x: 320, y: 510, major: true },
    { code: "BIO", name: "Bilbao", x: 480, y: 130, major: true },
    { code: "VGO", name: "Vigo", x: 110, y: 160 },
    { code: "TRG", name: "Tarragona", x: 720, y: 250 },
    { code: "CTG", name: "Cartagena", x: 580, y: 430 },
    { code: "MLG", name: "Málaga", x: 380, y: 490 },
    { code: "CAD", name: "Cádiz", x: 250, y: 510 },
    { code: "HUV", name: "Huelva", x: 220, y: 480 },
    { code: "FER", name: "Ferrol", x: 130, y: 100 },
    { code: "GIJ", name: "Gijón", x: 320, y: 110 },
    { code: "CST", name: "Castellón", x: 690, y: 280 },
    { code: "LPA", name: "Las Palmas", x: 240, y: 690, major: true },
    { code: "TFE", name: "S.C. Tenerife", x: 180, y: 700 },
  ];

  return (
    <svg viewBox="0 0 900 760" preserveAspectRatio="xMidYMid meet">
      {/* Stylized Iberia outline (illustrative, not geographically exact) */}
      <g stroke="var(--ink)" strokeWidth="1" fill="none" opacity="0.85">
        <path d="M 100 130 L 80 180 L 60 250 L 90 320 L 130 380 L 160 440 L 220 480 L 250 510 L 310 520 L 360 510 L 420 510 L 470 480 L 540 460 L 590 430 L 630 380 L 680 350 L 720 310 L 760 250 L 770 220 L 760 180 L 720 150 L 680 130 L 600 110 L 530 110 L 480 120 L 420 110 L 350 100 L 280 95 L 220 100 L 160 110 L 100 130 Z" fill="var(--paper-2)"/>
        {/* Portugal cutout */}
        <path d="M 80 180 L 90 220 L 100 280 L 140 360 L 200 460 L 220 480" fill="none" strokeDasharray="3 4" opacity="0.5" />
        {/* Balearic */}
        <ellipse cx="820" cy="290" rx="22" ry="11" fill="var(--paper-2)"/>
        <ellipse cx="855" cy="305" rx="14" ry="8" fill="var(--paper-2)"/>
        {/* Canary box */}
        <rect x="120" y="640" width="220" height="100" fill="var(--paper-2)" strokeDasharray="2 3" opacity="0.7" />
        <ellipse cx="240" cy="690" rx="16" ry="9" fill="var(--paper)" />
        <ellipse cx="180" cy="700" rx="14" ry="8" fill="var(--paper)" />
        <ellipse cx="210" cy="710" rx="9" ry="5" fill="var(--paper)" />
        <ellipse cx="280" cy="685" rx="8" ry="5" fill="var(--paper)" />
      </g>
      <text x="135" y="660" style={{fontFamily: "var(--mono)", fontSize: 8, letterSpacing: "0.15em", textTransform: "uppercase", fill: "var(--ink-3)"}}>ISLAS CANARIAS</text>
      <text x="800" y="270" style={{fontFamily: "var(--mono)", fontSize: 8, letterSpacing: "0.15em", textTransform: "uppercase", fill: "var(--ink-3)"}}>BALEARES</text>

      {pins.map(p => (
        <g key={p.code} className={`map-pin ${p.major ? "major" : ""}`} transform={`translate(${p.x}, ${p.y})`}>
          {p.major && <circle className="ring" r="6" />}
          <circle className="dot" r={p.major ? 3.5 : 2.2} />
          <text x="8" y="3">{p.name}</text>
        </g>
      ))}
    </svg>
  );
}

// ====== EXPORT ======
Object.assign(window, {
  BrandMark, Header, Footer, Figure, SpainMap, useReveal, useLang
});
