/* Illuma — Header (floating nav) + Footer */

const ABOUT_LINKS = [
  ["Our Story", "our-story.html"],
  ["What We Do", "what-we-do.html"],
  ["Our People", "our-people.html"],
  ["Community Engagement", "community-engagement.html"],
];

/* ---- Header search: index + logic --------------------------------------
   Real index over the site's Projects and News content. Town/location is
   indexed first so a town-name search (the primary use case) surfaces the
   right results; titles, excerpts and metadata are matched too. */
const SEARCH_PROJECTS = [
  { title: "Molong Battery",          location: "Molong, Central West NSW", excerpt: "In development \u00B7 Up to 150 MW / 600 MWh BESS",      href: "projects/molong-battery.html",        thumb: `${ASSET}/search-thumbs/energy-transition.jpg` },
  { title: "Kentbruck Battery",       location: "Kentbruck, VIC",           excerpt: "In development \u00B7 Battery energy storage system",     href: "projects/kentbruck-battery.html",     thumb: `${ASSET}/search-thumbs/wind-banner.jpg` },
  { title: "Moorabool Battery",       location: "Moorabool, VIC",           excerpt: "In development \u00B7 Battery energy storage system",     href: "projects/moorabool-battery.html",     thumb: `${ASSET}/search-thumbs/vicbb_industrialview-0736.jpg` },
  { title: "Bawurra Battery",         location: "Bawurra, NSW",             excerpt: "In development \u00B7 Battery energy storage system",     href: "projects/bawurra-battery.html",       thumb: `${ASSET}/search-thumbs/vicbb_industrialview-0629.jpg` },
  { title: "Victorian Big Battery",   location: "Geelong, Victoria",        excerpt: "Operational \u00B7 300 MW / 450 MWh",                     href: "projects/victorian-big-battery.html",  thumb: `${ASSET}/search-thumbs/vbb_image-1_202208.jpg` },
  { title: "Bulgana Green Power Hub", location: "Bulgana, VIC",             excerpt: "Operational \u00B7 204 MW wind + 20 MW battery",          href: "projects/bulgana-green-power-hub.html", thumb: `${ASSET}/search-thumbs/dji_0549-pano.jpg` },
  { title: "Numurkah Solar Farm",     location: "Numurkah, VIC",            excerpt: "Operational \u00B7 128 MW solar",                         href: "projects/numurkah-solar-farm.html",    thumb: `${ASSET}/search-thumbs/shh_neoen_sheep.059.jpg` },
];
const SEARCH_NEWS = [
  { title: "Introducing Illuma",                    location: "",                  excerpt: "A new platform created to help deliver the infrastructure Australia needs for what comes next.", href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/energy-transition.jpg` },
  { title: "Building a platform for momentum",      location: "",                  excerpt: "Leadership perspectives on energy infrastructure, delivery and long-term reliability.",         href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/update-photo.jpg` },
  { title: "Inside the future of battery storage",  location: "",                  excerpt: "How large-scale storage can support grid stability, reliability and future energy demand.",       href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/vbb-2.jpg` },
  { title: "Working alongside regional communities", location: "Bulgana, VIC",     excerpt: "How early, transparent engagement shapes stronger energy projects.",                            href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/bulgana-env.jpg` },
  { title: "Victorian Big Battery: two years on",   location: "Geelong, Victoria", excerpt: "Reflections on operating one of the largest batteries in the southern hemisphere.",              href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/vbb-1.jpg` },
  { title: "Solar and storage, working together",   location: "Numurkah, VIC",     excerpt: "Why pairing generation with storage is key to a reliable grid.",                                href: "article-introducing-illuma.html", thumb: `${ASSET}/search-thumbs/numurkah-1.jpg` },
];

function runSearch(rawQuery) {
  const q = (rawQuery || "").trim().toLowerCase();
  if (!q) return { projects: [], news: [] };
  const matches = (it) => (it.title + " " + it.location + " " + it.excerpt).toLowerCase().includes(q);
  // Town/location matches sort to the top (primary use case is a town name).
  const rank = (it) => (it.location.toLowerCase().includes(q) ? 0 : 1);
  const filt = (arr) => arr.filter(matches).sort((a, b) => rank(a) - rank(b));
  return { projects: filt(SEARCH_PROJECTS), news: filt(SEARCH_NEWS) };
}

function MagnifierIcon({ size = 20, color = "#732654" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="10.5" cy="10.5" r="6.75" stroke={color} strokeWidth="1.8" />
      <path d="M15.6 15.6 21 21" stroke={color} strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  );
}
function ClearIcon({ size = 20, color = "#732654" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="12" cy="12" r="9" stroke={color} strokeWidth="1.6" />
      <path d="M9 9l6 6M15 9l-6 6" stroke={color} strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

// Shared results dropdown — tabs (Projects / News with counts) + result list.
// Tab clicks are caught by a delegated [data-tab] listener on the search root.
function SearchResults({ results, tab, query }) {
  const list = tab === "Projects" ? results.projects : results.news;
  const total = results.projects.length + results.news.length;
  return (
    <div className="ill-search__panel">
      <div className="ill-search__tabs">
        <button type="button" data-tab="Projects" className={"ill-search__tab" + (tab === "Projects" ? " is-active" : "")}>Projects ({results.projects.length})</button>
        <button type="button" data-tab="News" className={"ill-search__tab" + (tab === "News" ? " is-active" : "")}>News ({results.news.length})</button>
      </div>
      <div className="ill-search__list">
        {list.length === 0 ? (
          <p className="ill-search__empty">No results found.</p>
        ) : list.map((it, i) => (
          <a key={i} href={it.href} className="ill-search__result">
            <span className="ill-search__result-text">
              <span className="ill-search__result-title">{it.title}</span>
              <span className="ill-search__result-excerpt">{it.excerpt}</span>
            </span>
            {it.thumb ? <span className="ill-search__result-thumb"><img src={it.thumb} alt="" /></span> : null}
          </a>
        ))}
      </div>
      {total > 0 && (
        <a className="ill-search__viewall" href={`search.html?q=${encodeURIComponent(query || "")}`}>
          <span>View all {total} results</span>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14" /><path d="M13 6l6 6-6 6" /></svg>
        </a>
      )}
    </div>
  );
}

// Desktop / tablet header search. Collapsed = pink icon box; click expands into
// an input with a clear (circle-x) icon; typing reveals the results dropdown.
// Native listeners throughout — the header is relocated to #ill-chrome by
// boot.js, so React's synthetic events never fire here.
function SearchBox() {
  const [expanded, setExpanded] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [tab, setTab] = React.useState(null);
  const rootRef = React.useRef(null);
  const toggleRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const expandedRef = React.useRef(false);
  expandedRef.current = expanded;

  React.useEffect(() => {
    const btn = toggleRef.current;
    if (!btn) return;
    const onClick = (e) => {
      e.stopPropagation();
      if (expandedRef.current) {
        if (inputRef.current) inputRef.current.value = "";
        setQuery(""); setTab(null); setExpanded(false);
      } else {
        setExpanded(true);
        setTimeout(() => inputRef.current && inputRef.current.focus(), 40);
      }
    };
    btn.addEventListener("click", onClick);
    return () => btn.removeEventListener("click", onClick);
  }, []);

  React.useEffect(() => {
    const inp = inputRef.current;
    if (!inp) return;
    const onInput = (e) => { setQuery(e.target.value); setTab(null); };
    inp.addEventListener("input", onInput);
    return () => inp.removeEventListener("input", onInput);
  }, []);

  // Delegated tab switching (panel re-mounts, root is stable).
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onClick = (e) => {
      const t = e.target.closest("[data-tab]");
      if (t) { e.stopPropagation(); setTab(t.getAttribute("data-tab")); }
    };
    root.addEventListener("click", onClick);
    return () => root.removeEventListener("click", onClick);
  }, []);

  React.useEffect(() => {
    if (!expanded) return;
    const onDoc = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setExpanded(false); };
    const onKey = (e) => { if (e.key === "Escape") setExpanded(false); };
    document.addEventListener("click", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("click", onDoc); document.removeEventListener("keydown", onKey); };
  }, [expanded]);

  const results = React.useMemo(() => runSearch(query), [query]);
  const effTab = tab || (results.projects.length ? "Projects" : (results.news.length ? "News" : "Projects"));
  const showPanel = expanded && query.trim().length > 0;

  return (
    <div className={"ill-search" + (expanded ? " is-expanded" : "")} ref={rootRef}>
      <div className="ill-search__field">
        <button ref={toggleRef} type="button" className="ill-search__toggle" aria-label={expanded ? "Clear search" : "Open search"}>
          {expanded ? <ClearIcon /> : <MagnifierIcon />}
        </button>
        <input ref={inputRef} type="text" className="ill-search__input" placeholder="Type a keyword" aria-label="Search" autoComplete="off" />
      </div>
      {showPanel && <SearchResults results={results} tab={effTab} query={query} />}
    </div>
  );
}

// Mobile search — lives inside the burger menu, full width, results inline.
function MobileSearch() {
  const [query, setQuery] = React.useState("");
  const [tab, setTab] = React.useState(null);
  const rootRef = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const inp = inputRef.current;
    if (!inp) return;
    const onInput = (e) => { setQuery(e.target.value); setTab(null); };
    inp.addEventListener("input", onInput);
    return () => inp.removeEventListener("input", onInput);
  }, []);
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onClick = (e) => {
      const t = e.target.closest("[data-tab]");
      if (t) { e.stopPropagation(); setTab(t.getAttribute("data-tab")); }
    };
    root.addEventListener("click", onClick);
    return () => root.removeEventListener("click", onClick);
  }, []);

  const results = React.useMemo(() => runSearch(query), [query]);
  const effTab = tab || (results.projects.length ? "Projects" : (results.news.length ? "News" : "Projects"));
  const showPanel = query.trim().length > 0;

  return (
    <div className="ill-msearch" ref={rootRef}>
      <div className="ill-msearch__field">
        <MagnifierIcon size={18} />
        <input ref={inputRef} type="text" className="ill-msearch__input" placeholder="Type a keyword" aria-label="Search" autoComplete="off" />
      </div>
      {showPanel && <SearchResults results={results} tab={effTab} query={query} />}
    </div>
  );
}

function Header() {
  const [open, setOpen] = React.useState(false);
  const [aboutOpen, setAboutOpen] = React.useState(false);
  const [aboutDrop, setAboutDrop] = React.useState(false);
  const burgerRef = React.useRef(null);
  const aboutAccRef = React.useRef(null);
  const aboutTrigRef = React.useRef(null);

  // boot.js moves .ill-header OUT of #stage (the React root) into #ill-chrome
  // so React's synthetic event delegation (which listens on #stage) never fires
  // for elements living in #ill-chrome. Attach native listeners directly to
  // the interactive buttons to bypass that limitation entirely.
  React.useEffect(() => {
    const btn = burgerRef.current;
    if (!btn) return;
    const toggle = (e) => {
      e.stopPropagation();
      setOpen((o) => !o);
    };
    btn.addEventListener("click", toggle);
    return () => btn.removeEventListener("click", toggle);
  }, []);

  // Mobile About accordion — native listener (see note above).
  React.useEffect(() => {
    const btn = aboutAccRef.current;
    if (!btn) return;
    const toggle = (e) => {
      e.stopPropagation();
      setAboutOpen((o) => !o);
    };
    btn.addEventListener("click", toggle);
    return () => btn.removeEventListener("click", toggle);
  }, []);

  // Desktop About dropdown — opens on click of the (non-link) trigger.
  React.useEffect(() => {
    const btn = aboutTrigRef.current;
    if (!btn) return;
    const toggle = (e) => {
      e.stopPropagation();
      setAboutDrop((o) => !o);
    };
    btn.addEventListener("click", toggle);
    return () => btn.removeEventListener("click", toggle);
  }, []);

  // Close when the user clicks anywhere outside the nav.
  React.useEffect(() => {
    if (!open && !aboutDrop) return;
    const close = () => { setOpen(false); setAboutOpen(false); setAboutDrop(false); };
    document.addEventListener("click", close);
    return () => document.removeEventListener("click", close);
  }, [open, aboutDrop]);

  return (
    <header className="ill-header">
      <nav className="ill-nav">
        <a href="index.html" aria-label="Illuma home">
          <img className="ill-nav__logo" src={`${ASSET}/logos/illuma-berry.svg`} alt="Illuma" />
        </a>
        <div className="ill-nav__items">
          <div className={"ill-drop" + (aboutDrop ? " open" : "")}>
            <span ref={aboutTrigRef} className="ill-nav__link" style={{ cursor: "pointer" }}>About Us <Chevron color="#732654" /></span>
            <div className="ill-drop__menu">
              {ABOUT_LINKS.map((l, i) => (
                <a key={i} className="ill-drop__item" href={l[1]}>{l[0]}</a>
              ))}
            </div>
          </div>
          <a className="ill-nav__link" href="projects.html">Projects</a>
          <a className="ill-nav__link" href="community.html">Community</a>
          <a className="ill-nav__link" href="news.html">News</a>
        </div>
        <button
          ref={burgerRef}
          className="ill-nav__burger"
          aria-label="Menu"
          aria-expanded={open}
        >
          <span style={{ transform: open ? "translateY(7px) rotate(45deg)" : "none" }} />
          <span style={{ opacity: open ? 0 : 1 }} />
          <span style={{ transform: open ? "translateY(-7px) rotate(-45deg)" : "none" }} />
        </button>
        <div className={"ill-nav__mobile" + (open ? " open" : "")}>
          <MobileSearch />
          <button
            ref={aboutAccRef}
            className={"ill-nav__mobile-acc" + (aboutOpen ? " open" : "")}
            aria-expanded={aboutOpen}
          >
            About Us <Chevron color="currentColor" />
          </button>
          <div className={"ill-nav__mobile-accpanel" + (aboutOpen ? " open" : "")}>
            <div className="ill-nav__mobile-acclist">
              {ABOUT_LINKS.map((l, i) => (
                <a key={i} href={l[1]} className="ill-nav__mobile-sub">{l[0]}</a>
              ))}
            </div>
          </div>
          <a href="projects.html">Projects</a>
          <a href="community.html">Community</a>
          <a href="news.html">News</a>
          <a href="contact.html" className="ill-nav__mobile-cta">Contact Us <ArrowUR color="currentColor" /></a>
        </div>
      </nav>
      <div className="ill-header__actions">
        <SearchBox />
        <a className="ill-btn ill-btn--berry ill-contact-btn" href="contact.html">Contact Us <ArrowUR color="currentColor" /></a>
      </div>
    </header>
  );
}

function Footer() {
  const ExtLink = () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 6, verticalAlign: "baseline", opacity: 0.8 }} aria-hidden="true">
      <path d="M14 4h6v6" />
      <path d="M20 4L11 13" />
      <path d="M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4" />
    </svg>
  );
  const col = (title, links) => (
    <div>
      <p className="ill-footer__col-title">{title}</p>
      {links.map((l, i) => (
        <a key={i} className="ill-footer__link" href={l[1]} {...(l[2] ? { target: "_blank", rel: "noopener noreferrer" } : {})}>{l[0]}</a>
      ))}
    </div>
  );
  const divider = () => <div aria-hidden="true" style={{ height: 1, background: "rgba(255,255,255,0.15)", width: "100%" }} />;
  return (
    <footer className="ill-footer">
      <div className="ill-main" style={{ display: "flex", flexDirection: "column", gap: 40 }}>
        <div className="ill-footer__top" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 40 }}>
          <div className="ill-footer__intro" style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <img src={`${ASSET}/logos/illuma-lightpink.svg`} alt="Illuma" style={{ width: 180, height: "auto" }} />
            <p style={{ margin: 0, fontSize: 20, lineHeight: 1.3, color: "var(--color-surface-pink)" }}>
              Powering what&rsquo;s next, now.
            </p>
          </div>
          <div className="ill-footer__badges" style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "flex-end", gap: 16 }}>
            <img src={`${ASSET}/logos/supply-nation-registered.png`} alt="Supply Nation Registered" style={{ width: 54, height: "auto", display: "block" }} />
            <img src={`${ASSET}/logos/clean-energy-council-best-practice.png`} alt="Clean Energy Council Best Practice Charter Signatory" style={{ width: 58, height: "auto", display: "block" }} />
          </div>
        </div>
        {divider()}
        <div className="ill-footer__groups" style={{ display: "flex", justifyContent: "space-between", gap: 40 }}>
          {col("Pages", [["Home", "index.html"], ["Projects", "projects.html"], ["Community", "community.html"], ["News", "news.html"], ["Contact us", "contact.html"]])}
          {col("About", [["Our Story", "our-story.html"], ["What We Do", "what-we-do.html"], ["Our People", "our-people.html"], ["Community Engagement", "community-engagement.html"]])}
          {col("Social", [["LinkedIn", "#"]])}
          {col("Legal", [["Privacy Policy", "privacy-policy.html", true], ["Terms & Conditions", "terms-and-conditions.html", true]])}
        </div>
        {divider()}
        <div className="ill-footer__bottom" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", fontSize: 15, color: "var(--color-surface-pink)", opacity: 0.92, fontWeight: 500, fontFamily: "var(--font-secondary)" }}>
          <span>&copy; 2026 Illuma. All rights reserved.</span>
          <span>Website by <a href="https://ven.com.au" target="_blank" rel="noopener noreferrer" className="ill-ven-credit" style={{ color: "inherit", textDecoration: "none" }}>Ven</a></span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Header, Footer, runSearch, SEARCH_PROJECTS, SEARCH_NEWS, MagnifierIcon, ClearIcon });
