/* ============================================================
   Agency BRN — Header + Hero + Trust strip + Problem
   ============================================================ */

const { useState, useEffect, useRef, useContext } = React;

/* ---------- Header ---------- */

const SERVICE_SLUGS = [
  "website-design-landing-pages",
  "google-business-profile-optimization",
  "crm-setup",
  "marketing-automation",
  "ai-powered-business-systems",
  "paid-traffic-strategy",
  "real-estate-rental-lead-systems",
];

function Header() {
  const { lang, setLang, t, basePath = "" } = useContext(window.LanguageContext);
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);
  const servicesCloseTimer = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
  }, [open]);

  // Close dropdowns on outside click
  useEffect(() => {
    if (!servicesOpen) return;
    const onDoc = (e) => {
      if (!e.target.closest(".nav__services")) setServicesOpen(false);
    };
    document.addEventListener("click", onDoc);
    return () => document.removeEventListener("click", onDoc);
  }, [servicesOpen]);

  const homeHref = (frag) => `${basePath}index.html${frag}`;
  const servicePageHref = (slug) => `${basePath}services/${slug}.html`;
  const servicesIndexHref = `${basePath}services/`;

  const navItems = [
    { href: homeHref("#home"), label: t.nav.home },
    { href: homeHref("#about"), label: t.nav.about },
    { isServices: true, label: t.nav.services },
    { href: homeHref("#industries"), label: t.nav.industries },
    { href: homeHref("#growth"), label: t.nav.growth },
    { href: homeHref("#blog"), label: t.nav.blog },
    { href: homeHref("#contact"), label: t.nav.contact },
  ];

  const openServices = () => {
    clearTimeout(servicesCloseTimer.current);
    setServicesOpen(true);
  };
  const scheduleCloseServices = () => {
    clearTimeout(servicesCloseTimer.current);
    servicesCloseTimer.current = setTimeout(() => setServicesOpen(false), 180);
  };

  // Service titles come from translations
  const serviceItems = (t.services.items || []).map((s, i) => ({
    slug: SERVICE_SLUGS[i],
    title: s.title,
  }));

  return (
    <header className={"header" + (scrolled ? " is-scrolled" : "")}>
      <div className="container header__inner">
        <a href={homeHref("#home")} className="logo">
          <span className="logo__mark">BRN</span>
          <span>Agency BRN</span>
        </a>

        <nav className="nav">
          {navItems.map((n, idx) =>
            n.isServices ? (
              <div
                key="services-dd"
                className={"nav__services" + (servicesOpen ? " is-open" : "")}
                onMouseEnter={openServices}
                onMouseLeave={scheduleCloseServices}
              >
                <button
                  type="button"
                  className="nav__services-trigger"
                  aria-haspopup="true"
                  aria-expanded={servicesOpen}
                  onClick={() => setServicesOpen((v) => !v)}
                >
                  {n.label}
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="6 9 12 15 18 9" />
                  </svg>
                </button>

                <div className="services-dd" role="menu">
                  <div className="services-dd__inner">
                    {serviceItems.map((it) => (
                      <a
                        key={it.slug}
                        href={servicePageHref(it.slug)}
                        className="services-dd__item"
                        role="menuitem"
                        onClick={() => setServicesOpen(false)}
                      >
                        <span className="services-dd__icon">
                          <ServiceMenuIcon slug={it.slug} />
                        </span>
                        <span className="services-dd__text">{it.title}</span>
                        <Icon.ArrowRight className="services-dd__arrow" width="14" height="14" />
                      </a>
                    ))}
                    <a
                      href={servicesIndexHref}
                      className="services-dd__view-all"
                      onClick={() => setServicesOpen(false)}
                    >
                      {t.nav.viewAllServices || "View All Services"}
                      <Icon.ArrowRight width="14" height="14" />
                    </a>
                  </div>
                </div>
              </div>
            ) : (
              <a key={n.href} href={n.href} onClick={() => setOpen(false)}>
                {n.label}
              </a>
            )
          )}
        </nav>

        <div className="header__right">
          <div className="lang-switch" role="tablist" aria-label="Language">
            {["en", "pt", "es"].map((code) => (
              <button
                key={code}
                role="tab"
                aria-selected={lang === code}
                className={lang === code ? "is-active" : ""}
                onClick={() => setLang(code)}
              >
                {code.toUpperCase()}
              </button>
            ))}
          </div>
          <a href={homeHref("#contact")} className="btn btn--primary btn--sm header__cta">
            {t.ctaShort}
            <Icon.ArrowRight className="arrow" width="14" height="14" />
          </a>
          <button
            className="menu-toggle"
            aria-label="Menu"
            onClick={() => setOpen((o) => !o)}
          >
            {open ? <Icon.Close /> : <Icon.Menu />}
          </button>
        </div>
      </div>

      <div className={"mobile-menu" + (open ? " is-open" : "")}>
        {navItems.map((n, idx) =>
          n.isServices ? (
            <div key="m-services" className="mobile-menu__group">
              <button
                type="button"
                className={"mobile-menu__group-trigger" + (mobileServicesOpen ? " is-open" : "")}
                onClick={() => setMobileServicesOpen((v) => !v)}
                aria-expanded={mobileServicesOpen}
              >
                {n.label}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </button>
              {mobileServicesOpen && (
                <div className="mobile-menu__sub">
                  {serviceItems.map((it) => (
                    <a
                      key={it.slug}
                      href={servicePageHref(it.slug)}
                      onClick={() => setOpen(false)}
                    >
                      {it.title}
                    </a>
                  ))}
                  <a href={servicesIndexHref} onClick={() => setOpen(false)} className="mobile-menu__view-all">
                    {t.nav.viewAllServices || "View All Services"} →
                  </a>
                </div>
              )}
            </div>
          ) : (
            <a key={n.href} href={n.href} onClick={() => setOpen(false)}>
              {n.label}
            </a>
          )
        )}
        <a href={homeHref("#contact")} className="btn btn--primary" onClick={() => setOpen(false)}>
          {t.cta}
        </a>
      </div>
    </header>
  );
}

/* Small inline icon picker for the services dropdown — reuses Icon set */
function ServiceMenuIcon({ slug }) {
  const map = {
    "website-design-landing-pages": Icon.Web,
    "google-business-profile-optimization": Icon.Gmaps,
    "crm-setup": Icon.Crm,
    "marketing-automation": Icon.Automation,
    "ai-powered-business-systems": Icon.Ai,
    "paid-traffic-strategy": Icon.Ads,
    "real-estate-rental-lead-systems": Icon.House,
  };
  const I = map[slug] || Icon.Sparkle;
  return <I width="18" height="18" />;
}

window.ServiceMenuIcon = ServiceMenuIcon;
window.SERVICE_SLUGS = SERVICE_SLUGS;

/* ---------- Hero ---------- */
function Hero() {
  const { t } = useContext(window.LanguageContext);
  const c = t.hero.cards;
  return (
    <section className="hero" id="home">
      <div className="grid-overlay" />
      <div className="container hero__grid">
        <div className="hero__copy">
          <span className="eyebrow"><span className="dot" /> {t.hero.eyebrow}</span>
          <h1>
            {t.hero.h1A}
            <span className="text-grad">{t.hero.h1Grad}</span>
            {t.hero.h1B}
          </h1>
          <p className="hero__sub">{t.hero.sub}</p>
          <div className="hero__ctas">
            <a href="#contact" className="btn btn--primary btn--lg">
              {t.hero.ctaPrimary}
              <Icon.ArrowRight className="arrow" />
            </a>
            <a href="#services" className="btn btn--ghost-dark btn--lg">
              {t.hero.ctaSecondary}
            </a>
          </div>
          <div className="hero__trustline">
            <span className="trust-flag">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-7 8-13a8 8 0 1 0-16 0c0 6 8 13 8 13z" /><circle cx="12" cy="9" r="2.6" /></svg>
            </span>
            <span>{t.hero.trustLine}</span>
          </div>
          <div className="hero__trust-secondary">{t.hero.trustLocal}</div>
        </div>

        <div className="hero__visual">
          {/* 1. Website performance */}
          <div className="float-card hcard hcard--website">
            <div className="mini-h">
              <span>{c.website.label}</span>
              <span style={{ color: "#34D399", fontSize: 9, fontWeight: 700, letterSpacing: "0.06em" }}>● LIVE</span>
            </div>
            <div className="hcard__row">
              <div className="hcard__metric">
                <div className="hcard__label">{c.website.uptime}</div>
                <div className="hcard__value hcard__value--sm">99.98<span style={{ fontSize: 12, opacity: 0.6 }}>%</span></div>
              </div>
              <div className="hcard__metric">
                <div className="hcard__label">{c.website.load}</div>
                <div className="hcard__value hcard__value--sm">0.8<span style={{ fontSize: 12, opacity: 0.6 }}>s</span></div>
              </div>
            </div>
            <div className="hcard__divider" />
            <div className="hcard__visitors">
              <div className="hcard__label">{c.website.visitors}</div>
              <div className="hcard__visitors-row">
                <strong>2,847</strong>
                <span className="hcard__delta">↑ 12%</span>
              </div>
            </div>
          </div>

          {/* 2. CRM pipeline */}
          <div className="float-card hcard hcard--crm">
            <div className="mini-h">
              <span>{c.crm.label}</span>
              <span className="dot-cluster"><i className="on" /><i className="on" /><i /></span>
            </div>
            <div className="crm-stages">
              {[
                { label: c.crm.new, count: 12, color: "linear-gradient(135deg, #3B82F6, #06B6D4)" },
                { label: c.crm.qualified, count: 7, color: "linear-gradient(135deg, #8B5CF6, #EC4899)" },
                { label: c.crm.booked, count: 4, color: "linear-gradient(135deg, #10B981, #22D3EE)" },
              ].map((s, i) => (
                <div key={i} className="crm-stage">
                  <div className="crm-stage__head">
                    <span className="crm-stage__label">{s.label}</span>
                    <span className="crm-stage__count">{s.count}</span>
                  </div>
                  <div className="crm-stage__avatars">
                    {Array.from({ length: Math.min(s.count, 4) }).map((_, j) => (
                      <span key={j} className="crm-avatar" style={{ background: s.color, transform: `translateX(${-j * 6}px)`, zIndex: 4 - j }} />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 3. Google Business visibility */}
          <div className="float-card hcard hcard--gbp">
            <div className="mini-h">
              <span>{c.gbp.label}</span>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M22 12c0-5.5-4.5-10-10-10S2 6.5 2 12c0 5 3.7 9.1 8.4 9.9V15H8v-3h2.4V9.8c0-2.4 1.4-3.7 3.6-3.7 1 0 2.1.2 2.1.2v2.4h-1.2c-1.2 0-1.5.7-1.5 1.5V12h2.6l-.4 3h-2.2v6.9C18.3 21.1 22 17 22 12z" fill="#1A73E8" />
              </svg>
            </div>
            <div className="gbp-row">
              <div className="gbp-rating">
                <div className="gbp-rating__num">4.9</div>
                <div className="gbp-stars">★★★★★</div>
                <div className="gbp-reviews">142 {c.gbp.reviews}</div>
              </div>
              <div className="gbp-map">
                <svg viewBox="0 0 60 60" style={{ width: "100%", height: "100%" }}>
                  <defs>
                    <linearGradient id="mapg" x1="0" y1="0" x2="60" y2="60">
                      <stop offset="0" stopColor="#1E293B" />
                      <stop offset="1" stopColor="#0F172A" />
                    </linearGradient>
                  </defs>
                  <rect width="60" height="60" rx="8" fill="url(#mapg)" />
                  <g opacity="0.25" stroke="rgba(255,255,255,0.3)" strokeWidth="0.4">
                    <line x1="0" y1="20" x2="60" y2="14" />
                    <line x1="0" y1="38" x2="60" y2="34" />
                    <line x1="18" y1="0" x2="22" y2="60" />
                    <line x1="40" y1="0" x2="44" y2="60" />
                  </g>
                  <circle cx="30" cy="32" r="14" fill="#3B82F6" opacity="0.15" />
                  <circle cx="30" cy="32" r="3" fill="#3B82F6" stroke="#fff" strokeWidth="1.5" />
                </svg>
              </div>
            </div>
            <div className="gbp-status">
              <span className="status-dot" />
              {c.gbp.appears}
            </div>
          </div>

          {/* 4. AI assistant */}
          <div className="float-card hcard hcard--ai">
            <div className="mini-h">
              <span>{c.ai.label}</span>
              <Icon.Sparkle style={{ width: 12, height: 12, color: "#22D3EE" }} />
            </div>
            <div className="ai-row">
              <div className="ai-glyph">
                <Icon.Sparkle style={{ width: 14, height: 14 }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="ai-title">{c.ai.title}</div>
                <div className="ai-body">{c.ai.body}</div>
              </div>
            </div>
            <div className="ai-progress"><span /></div>
            <div className="ai-channels">
              <span className="chan">SMS</span>
              <span className="chan">Email</span>
              <span className="chan">WhatsApp</span>
            </div>
          </div>

          {/* 5. Lead growth analytics */}
          <div className="float-card hcard hcard--analytics">
            <div className="mini-h">
              <span>{c.analytics.label}</span>
              <span style={{ fontSize: 10, color: "rgba(255,255,255,0.4)" }}>30d</span>
            </div>
            <div className="analytics-top">
              <div className="analytics-value">{c.analytics.value}</div>
              <div className="analytics-meta">
                <div className="analytics-delta">↑ {c.analytics.delta}</div>
                <div className="analytics-caption">{c.analytics.caption}</div>
              </div>
            </div>
            <svg className="analytics-chart" viewBox="0 0 200 60" preserveAspectRatio="none">
              <defs>
                <linearGradient id="chartg" x1="0" y1="0" x2="0" y2="60">
                  <stop offset="0" stopColor="#3B82F6" stopOpacity="0.4" />
                  <stop offset="1" stopColor="#3B82F6" stopOpacity="0" />
                </linearGradient>
                <linearGradient id="chartline" x1="0" y1="0" x2="200" y2="0">
                  <stop offset="0" stopColor="#3B82F6" />
                  <stop offset="1" stopColor="#22D3EE" />
                </linearGradient>
              </defs>
              <path d="M0,48 L20,44 L40,46 L60,38 L80,40 L100,30 L120,28 L140,20 L160,22 L180,14 L200,8 L200,60 L0,60 Z" fill="url(#chartg)" />
              <path d="M0,48 L20,44 L40,46 L60,38 L80,40 L100,30 L120,28 L140,20 L160,22 L180,14 L200,8" fill="none" stroke="url(#chartline)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              <circle cx="200" cy="8" r="3" fill="#22D3EE" />
              <circle cx="200" cy="8" r="6" fill="#22D3EE" opacity="0.3" />
            </svg>
          </div>

          {/* 6. Automation status */}
          <div className="float-card hcard hcard--automation">
            <div className="mini-h">
              <span>{c.automation.label}</span>
              <span className="live-pill"><i /> {c.automation.live}</span>
            </div>
            <div className="auto-main">
              <div className="auto-orbit">
                <svg viewBox="0 0 60 60" width="46" height="46">
                  <circle cx="30" cy="30" r="22" fill="none" stroke="rgba(34,211,238,0.2)" strokeWidth="1.5" strokeDasharray="3 3" />
                  <circle cx="30" cy="30" r="12" fill="none" stroke="rgba(59,130,246,0.4)" strokeWidth="1.5" />
                  <circle cx="30" cy="30" r="5" fill="url(#autog)" />
                  <defs>
                    <radialGradient id="autog">
                      <stop offset="0" stopColor="#22D3EE" />
                      <stop offset="1" stopColor="#3B82F6" />
                    </radialGradient>
                  </defs>
                </svg>
                <span className="orbit-dot orbit-dot--1" />
                <span className="orbit-dot orbit-dot--2" />
                <span className="orbit-dot--3" />
              </div>
              <div className="auto-stats">
                <div className="auto-count">{c.automation.count.split(" ")[0]}</div>
                <div className="auto-label">{c.automation.running}</div>
              </div>
            </div>
          </div>

          {/* 7. Review growth */}
          <div className="float-card hcard hcard--reviews">
            <div className="mini-h">
              <span>{c.reviews.label}</span>
              <span style={{ color: "#FBBF24", fontSize: 11, letterSpacing: 1 }}>★</span>
            </div>
            <div className="reviews-top">
              <div className="reviews-value">{c.reviews.value}</div>
              <div className="reviews-caption">{c.reviews.caption}</div>
            </div>
            <div className="reviews-bars">
              {[26, 40, 32, 58, 44, 70, 88].map((h, i) => (
                <i key={i} style={{ height: h + "%" }} />
              ))}
            </div>
          </div>

          {/* 8. Quote requests */}
          <div className="float-card hcard hcard--quotes">
            <div className="mini-h">
              <span>{c.quotes.label}</span>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: "rgba(255,255,255,0.5)" }}>
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
              </svg>
            </div>
            <div className="quotes-row">
              <div className="quotes-value">{c.quotes.value}</div>
              <div className="quotes-caption">{c.quotes.caption}</div>
            </div>
            <div className="quotes-conv">
              <div className="quotes-conv__label">{c.quotes.conversion}</div>
              <div className="quotes-conv__track">
                <span style={{ width: c.quotes.conversionValue }} />
              </div>
              <div className="quotes-conv__val">{c.quotes.conversionValue}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Trust strip ---------- */
function TrustStrip() {
  const { t } = useContext(window.LanguageContext);
  const icons = [<Icon.Web />, <Icon.Gmaps />, <Icon.Crm />, <Icon.Automation />, <Icon.Ai />];
  return (
    <div className="trust-strip">
      <div className="container trust-strip__inner">
        <span className="trust-strip__label">{t.trust.label}</span>
        <div className="trust-strip__items">
          {t.trust.items.map((label, i) => (
            <span key={i} className="trust-strip__item">
              <span className="ic">{React.cloneElement(icons[i], { width: 18, height: 18 })}</span>
              {label}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- Problem ---------- */
function Problem() {
  const { t } = useContext(window.LanguageContext);
  return (
    <section className="section section--light" id="about">
      <div className="container">
        <div className="section__header reveal">
          <span className="eyebrow"><span className="dot" /> {t.problem.eyebrow}</span>
          <h2>
            {t.problem.h2A}
            <span className="text-grad">{t.problem.h2Grad}</span>
            {t.problem.h2B}
          </h2>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: "clamp(36px, 5vw, 64px)", alignItems: "start" }}
             className="problem__grid">
          <div className="reveal">
            <p style={{ fontSize: 17, lineHeight: 1.65, color: "var(--ink-500)", marginBottom: 22 }}>
              {t.problem.body}
            </p>
            <p style={{ fontSize: 17, lineHeight: 1.65, color: "var(--ink-900)", fontWeight: 500 }}>
              {t.problem.body2}
            </p>
          </div>

          <div className="problem-stats reveal" data-delay="1"
               style={{ display: "grid", gap: 14 }}>
            {t.problem.stats.map((s, i) => (
              <div key={i} style={{
                background: "#fff",
                border: "1px solid var(--ink-100)",
                borderRadius: "var(--r-xl)",
                padding: "28px 30px",
                display: "flex",
                alignItems: "center",
                gap: 24,
                boxShadow: "var(--shadow-xs)",
              }}>
                <div style={{
                  fontFamily: "var(--font-display)",
                  fontWeight: 800,
                  fontSize: 48,
                  lineHeight: 1,
                  letterSpacing: "-0.04em",
                  background: "linear-gradient(135deg, #2563EB, #06B6D4)",
                  WebkitBackgroundClip: "text",
                  backgroundClip: "text",
                  color: "transparent",
                  flexShrink: 0,
                  minWidth: 92,
                }}>
                  {s.value}
                </div>
                <div style={{ fontSize: 15, color: "var(--ink-500)", lineHeight: 1.5 }}>
                  {s.label}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .problem__grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

window.Header = Header;
window.Hero = Hero;
window.TrustStrip = TrustStrip;
window.Problem = Problem;
