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

// ─────────── Hooks ───────────
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ─────────── Inline SVGs ───────────
const ArchOrnament = ({ stroke = "currentColor", width = 160 }) => (
  <svg width={width} viewBox="0 0 160 200" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    <path
      d="M10 195 V70 C10 40, 35 12, 80 12 C 125 12, 150 40, 150 70 V195"
      stroke={stroke}
      strokeWidth="1.4"
      strokeLinecap="round"
      opacity="0.85"
    />
    <path
      d="M22 195 V72 C22 48, 42 24, 80 24 C 118 24, 138 48, 138 72 V195"
      stroke={stroke}
      strokeWidth="1"
      strokeLinecap="round"
      opacity="0.45"
    />
    {/* sun */}
    <circle cx="80" cy="62" r="6" fill={stroke} opacity="0.9" />
    {[...Array(12)].map((_, i) => {
      const a = (i * Math.PI * 2) / 12;
      const x1 = 80 + Math.cos(a) * 12, y1 = 62 + Math.sin(a) * 12;
      const x2 = 80 + Math.cos(a) * 17, y2 = 62 + Math.sin(a) * 17;
      return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={stroke} strokeWidth="1.1" strokeLinecap="round" />;
    })}
    {/* olive sprig */}
    <path d="M80 110 V160" stroke={stroke} strokeWidth="1" opacity="0.7" />
    <ellipse cx="68" cy="120" rx="6" ry="2.5" fill={stroke} opacity="0.55" transform="rotate(-30 68 120)" />
    <ellipse cx="92" cy="125" rx="6" ry="2.5" fill={stroke} opacity="0.55" transform="rotate(30 92 125)" />
    <ellipse cx="65" cy="135" rx="6" ry="2.5" fill={stroke} opacity="0.55" transform="rotate(-30 65 135)" />
    <ellipse cx="95" cy="140" rx="6" ry="2.5" fill={stroke} opacity="0.55" transform="rotate(30 95 140)" />
    <ellipse cx="70" cy="150" rx="5" ry="2.2" fill={stroke} opacity="0.55" transform="rotate(-30 70 150)" />
  </svg>
);

const OliveBranch = ({ width = 90, color = "currentColor" }) => (
  <svg width={width} viewBox="0 0 90 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    <path d="M2 9 H88" stroke={color} strokeWidth="0.9" opacity="0.5" />
    <ellipse cx="20" cy="6" rx="5" ry="2" fill={color} opacity="0.7" transform="rotate(-20 20 6)" />
    <ellipse cx="35" cy="12" rx="5" ry="2" fill={color} opacity="0.7" transform="rotate(20 35 12)" />
    <ellipse cx="55" cy="6" rx="5" ry="2" fill={color} opacity="0.7" transform="rotate(-20 55 6)" />
    <ellipse cx="70" cy="12" rx="5" ry="2" fill={color} opacity="0.7" transform="rotate(20 70 12)" />
  </svg>
);

const Arrow = () => (
  <svg width="16" height="10" viewBox="0 0 16 10" fill="none" aria-hidden="true">
    <path d="M1 5 H14 M10 1 L14 5 L10 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

// ─────────── Nav ───────────
function Nav({ t, lang, setLang, paletteName }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
  }, [menuOpen]);

  const links = [
    { href: "#about", label: t.nav.about },
    { href: "#process", label: t.nav.process },
    { href: "#regions", label: t.nav.regions },
    { href: "#contact", label: t.nav.contact },
    { href: "#faqs", label: t.nav.faqs }
  ];

  return (
    <React.Fragment>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div className="container nav-inner">
          <a href="#top" className="nav-logo" onClick={() => setMenuOpen(false)}>
            <img src="assets/favicon.png" alt="Spanish Heritage" />
            <div>
              <div className="nav-logo-text">Spanish Heritage</div>
              <div className="nav-logo-sub">Fine Spanish Goods</div>
            </div>
          </a>
          <div className="nav-links">
            {links.map(l => <a key={l.href} href={l.href}>{l.label}</a>)}
          </div>
          <div className="nav-right">
            <div className="lang-switch" role="tablist">
              {["en", "es", "ar"].map((code) => (
                <button
                  key={code}
                  className={lang === code ? "active" : ""}
                  onClick={() => setLang(code)}
                  aria-label={code}
                >
                  {code.toUpperCase()}
                </button>
              ))}
            </div>
            <a href="#contact" className="btn btn-primary nav-cta-desktop" style={{padding: "0.7rem 1.1rem", fontSize: "0.72rem"}}>
              {t.nav.cta} <span className="arrow"><Arrow /></span>
            </a>
            <button
              className={`nav-toggle ${menuOpen ? "open" : ""}`}
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label="Menu"
              aria-expanded={menuOpen}
            >
              <span className="bar"></span>
            </button>
          </div>
        </div>
      </nav>
      <div className={`mobile-menu ${menuOpen ? "open" : ""}`}>
        {links.map(l => (
          <a key={l.href} href={l.href} onClick={() => setMenuOpen(false)}>{l.label}</a>
        ))}
        <div className="lang-row">
          <div className="lang-switch" role="tablist">
            {["en", "es", "ar"].map((code) => (
              <button
                key={code}
                className={lang === code ? "active" : ""}
                onClick={() => setLang(code)}
                aria-label={code}
              >
                {code.toUpperCase()}
              </button>
            ))}
          </div>
          <a href="#contact" className="btn btn-primary" onClick={() => setMenuOpen(false)} style={{padding: "0.7rem 1.1rem", fontSize: "0.72rem"}}>
            {t.nav.cta} <span className="arrow"><Arrow /></span>
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}

// ─────────── Hero ───────────
function Hero({ t }) {
  return (
    <section className="hero" id="top">
      <div className="hero-bg">
        <img
          src="https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1920&q=80&auto=format&fit=crop"
          alt="Paisaje rural español al atardecer"
          loading="eager"
        />
      </div>
      <div className="container hero-content">
        <div className="hero-arch">
          <img src="assets/isotipo.png" alt="" style={{width: "100%", height: "auto", filter: "drop-shadow(0 4px 20px rgba(0,0,0,0.3))"}} />
        </div>
        <div className="eyebrow" style={{color:"rgba(247,241,227,0.78)", marginBottom: "1.2rem"}}>
          <span>{t.hero.arch}</span><span className="dot"></span><span>Valencia · UAE</span>
        </div>
        <h1>
          {t.hero.title_a} <em>{t.hero.title_em}</em>{t.hero.title_b}
        </h1>
        <p className="hero-tagline">{t.hero.tagline}</p>
        <div className="hero-meta">
          <span className="pin"></span>
          <span>{t.hero.meta1}</span>
          <span className="pin" style={{opacity: 0.7}}></span>
          <span>{t.hero.meta2}</span>
          <span className="pin"></span>
        </div>
      </div>
    </section>
  );
}

// ─────────── Marquee ───────────
function Marquee({ items }) {
  const list = [...items, ...items];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {list.map((it, i) => (
          <span key={i}>{it}<span className="sep">✦</span></span>
        ))}
      </div>
    </div>
  );
}

// ─────────── Section Head ───────────
function SectionHead({ eyebrow, num, title_a, title_em, title_b }) {
  return (
    <div className="section-head container">
      <div className="reveal">
        <div className="eyebrow">{eyebrow}</div>
      </div>
      <h2 className="reveal reveal-delay-1">
        {title_a} <em>{title_em}</em>{title_b}
      </h2>
    </div>
  );
}

// ─────────── About ───────────
function About({ t }) {
  return (
    <section className="section" id="about">
      <SectionHead {...t.about} />
      <div className="container">
        <div className="about-grid">
          <div className="about-text reveal">
            <p className="lead" style={{marginBottom: "1.5rem"}}>{t.about.p1}</p>
            <p>{t.about.p2}</p>
            <p>{t.about.p3}</p>
            <div className="signature">{t.about.signature}</div>
          </div>
          <div className="about-img reveal reveal-delay-2">
            <img
              src="assets/about-cava-quesos.jpg"
              alt="Cava de afinado con quesos artesanos de corteza enmohecida sobre estantería de madera"
              loading="lazy"
            />
          </div>
        </div>
        <div className="values">
          {t.about.values.map((v, i) => (
            <div key={i} className={`value-card reveal reveal-delay-${i+1}`}>
              <div className="num">{v.num}</div>
              <h3>{v.title}</h3>
              <p>{v.text}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── Process ───────────
function Process({ t }) {
  return (
    <section className="section process" id="process">
      <div className="zellige"></div>
      <SectionHead {...t.process} />
      <div className="container">
        <div className="process-steps">
          {t.process.steps.map((s, i) => (
            <div key={i} className={`step reveal reveal-delay-${(i%3)+1}`}>
              <span className="step-num">0{i+1}</span>
              <h3>{s.title}</h3>
              <p>{s.text}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── Regions ───────────
function Regions({ t }) {
  const imgs = [
    "https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=900&q=80&auto=format&fit=crop", // País Vasco — green mountain pasture (Aralar feel)
    "assets/region-extremadura.jpg", // Extremadura — dehesa con encinas y ganado pastando
    "assets/region-la-mancha.jpg", // La Mancha — molinos de Consuegra
    "assets/region-picos-europa.jpg", // Picos de Europa — vaca pastando, cumbres calizas y lago de fondo (Covadonga)
    "assets/region-albarracin.jpg"  // Sierra de Albarracín — castillo de Peracense, piedra rojiza
  ];
  return (
    <section className="section bg-paper" id="regions">
      <SectionHead {...t.regions} />
      <div className="container">
        <p className="lead reveal" style={{marginBottom: "1rem"}}>{t.regions.lead}</p>
        <div className="regions-grid">
          {t.regions.cards.map((c, i) => (
            <article key={i} className={`region-card reveal reveal-delay-${(i%3)+1}`}>
              <div className="region-img">
                <div className="region-do">{c.do}</div>
                <img src={imgs[i % imgs.length]} alt={`Paisaje de ${c.name}`} loading="lazy" />
              </div>
              <div className="region-body">
                <h3>{c.name}</h3>
                <p>{c.text}</p>
                <div className="region-cheeses">
                  {c.cheeses.map((ch, j) => <span key={j}>{ch}</span>)}
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── FAQs ───────────
function FAQs({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faqs">
      <SectionHead {...t.faqs} />
      <div className="container">
        <div className="faq-list reveal" style={{maxWidth: "880px"}}>
          {t.faqs.items.map((item, i) => (
            <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{item.q}</span>
                <span className="plus" aria-hidden="true"></span>
              </button>
              <div className="faq-a">{item.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── Contact ───────────
function Contact({ t, lang }) {
  const [status, setStatus] = useState(null); // null | 'sending' | 'thanks' | 'error'
  const formRef = useRef(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    const data = new FormData(formRef.current);
    try {
      // Envío vía Web3Forms (https://web3forms.com).
      // La access_key viaja como input hidden dentro del <form>.
      const resp = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        body: data
      });
      const json = await resp.json().catch(() => ({}));
      if (resp.ok && json.success) {
        setStatus("thanks");
        formRef.current.reset();
      } else {
        setStatus("error");
      }
    } catch (err) {
      setStatus("error");
    }
  };

  return (
    <section className="section contact" id="contact">
      <SectionHead {...t.contact} />
      <div className="container">
        <p className="lead reveal" style={{maxWidth:"60ch", marginBottom: "3.5rem"}}>{t.contact.lead}</p>

        <form ref={formRef} onSubmit={handleSubmit} className="contact-form reveal">
          {/* Web3Forms — endpoint: https://api.web3forms.com/submit */}
          <input type="hidden" name="access_key" value="a78e9c02-0449-4f02-8eea-0ba4390fcea4" />
          <input type="hidden" name="subject" value="Spanish Heritage · Nuevo contacto desde la web" />
          <input type="hidden" name="from_name" value="Spanish Heritage Web" />
          {/* Honeypot anti-spam (Web3Forms ignora envíos con este campo relleno) */}
          <input type="checkbox" name="botcheck" style={{display:"none"}} tabIndex="-1" />

          <div className="form-grid">
            <div className="field">
              <label>{t.contact.form.name}</label>
              <input type="text" name="Nombre" required />
            </div>
            <div className="field">
              <label>{t.contact.form.company}</label>
              <input type="text" name="Empresa" />
            </div>
            <div className="field">
              <label>{t.contact.form.email}</label>
              <input type="email" name="Email" required />
            </div>
            <div className="field">
              <label>{t.contact.form.phone}</label>
              <input type="tel" name="Telefono" />
            </div>
            <div className="field full">
              <label>{t.contact.form.type}</label>
              <select name="Tipo de negocio" defaultValue="">
                <option value="" disabled></option>
                {t.contact.form.types.map((typ, i) => <option key={i} value={typ}>{typ}</option>)}
              </select>
            </div>
            <div className="field full">
              <label>{t.contact.form.message}</label>
              <textarea name="Mensaje" rows="4" required></textarea>
            </div>
          </div>
          <div className="form-actions">
            <button type="submit" className="btn btn-submit" disabled={status === "sending"}>
              {status === "sending" ? "..." : t.contact.form.submit}
              <span className="arrow"><Arrow /></span>
            </button>
            {status === "thanks" && <div className="form-msg">{t.contact.form.thanks}</div>}
            {status === "error" && <div className="form-msg" style={{color: "var(--terracotta)"}}>{t.contact.form.error}</div>}
          </div>
        </form>

        <div className="contact-info-row reveal reveal-delay-1">
          <div className="contact-info-item">
            <div className="label">{t.contact.labels.email}</div>
            <a href="mailto:spanishheritagefood@gmail.com" className="value">spanishheritagefood@gmail.com</a>
          </div>
          <div className="contact-info-item">
            <div className="label">{t.contact.labels.based}</div>
            <div className="value">{t.contact.based_val}</div>
          </div>
          <div className="contact-info-item">
            <div className="label">{t.contact.labels.phone}</div>
            <div className="value">{t.contact.phone_val}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────── Footer ───────────
function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div className="footer-brand">
          <img src="assets/favicon.png" alt="" />
          <div>
            <div className="footer-brand-text">Spanish Heritage</div>
            <div style={{fontSize: "0.72rem", letterSpacing: "0.2em", textTransform: "uppercase", marginTop: "3px", color: "var(--gold)"}}>{t.footer.tagline}</div>
          </div>
        </div>
        <div>{t.footer.copy}</div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, Hero, Marquee, About, Process, Regions, FAQs, Contact, Footer,
  ArchOrnament, OliveBranch, useReveal
});
