// Sarpah app — React 18, hash-based router, markdown pages, forms, search.
// All UI rendered from window.SARPAH_ROUTES + content/*.md files.

const { useEffect, useMemo, useRef, useState, useCallback, useLayoutEffect } = React;

/* ============================================================
   Routing
   ============================================================ */

function getRoute() {
  const h = window.location.hash || "#/";
  return h.replace(/^#/, "") || "/";
}

function navigate(path, opts = {}) {
  if (opts.replace) {
    history.replaceState(null, "", "#" + path);
  } else {
    window.location.hash = path;
  }
  window.scrollTo({ top: 0, behavior: "instant" });
}

function useRoute() {
  const [path, setPath] = useState(getRoute());
  useEffect(() => {
    const handler = () => setPath(getRoute());
    window.addEventListener("hashchange", handler);
    return () => window.removeEventListener("hashchange", handler);
  }, []);
  return path;
}

function findRoute(path) {
  return window.SARPAH_ROUTES.find(r => r.slug === path);
}

function routesBySection(section) {
  return window.SARPAH_ROUTES.filter(r => r.section === section);
}

function routesByGroup(group) {
  return window.SARPAH_ROUTES.filter(r => r.group === group);
}

/* ============================================================
   Markdown loading
   ============================================================ */

const mdCache = new Map();

async function loadMarkdown(file) {
  if (mdCache.has(file)) return mdCache.get(file);
  const res = await fetch(file);
  if (!res.ok) throw new Error("Failed to load: " + file);
  const text = await res.text();
  const parsed = window.SarpahMD.render(text);
  mdCache.set(file, parsed);
  return parsed;
}

function useMarkdown(file) {
  const [state, setState] = useState({ loading: true });
  useEffect(() => {
    if (!file) { setState({ loading: false }); return; }
    let alive = true;
    setState({ loading: true });
    loadMarkdown(file).then(p => { if (alive) setState({ loading: false, ...p }); })
                      .catch(e => { if (alive) setState({ loading: false, error: e.message }); });
    return () => { alive = false; };
  }, [file]);
  return state;
}

/* ============================================================
   Brand + nav + footer
   ============================================================ */

function Brand({ small }) {
  return (
    <a href="#/" className="brand" aria-label="Sarpah Freighters & Logistics">
      <span className="brand__word">Sarpah</span>
      <span className="brand__amp">Freighters &amp; Logistics</span>
    </a>
  );
}

function TopNav({ onSearch, onMobileOpen }) {
  const path = useRoute();
  const isActive = (item) => {
    if (item.slug === "/" && path === "/") return true;
    if (item.slug !== "/" && (path === item.slug)) return true;
    if (item.match) return item.match.some(p => path.startsWith(p));
    return false;
  };
  return (
    <nav className="site-nav no-print" role="navigation" aria-label="Primary">
      <div className="site-nav__inner">
        <Brand small />
        <ul className="nav-list">
          {window.SARPAH_PRIMARY_NAV.map(item => (
            <li key={item.slug}>
              <a href={"#" + item.slug} className={isActive(item) ? "is-active" : ""}>{item.label}</a>
            </li>
          ))}
        </ul>
        <div className="nav-actions">
          <button className="search-trigger" onClick={onSearch} aria-label="Search">
            <SearchIcon />
            <span>Search…</span>
            <kbd className="search-trigger__hint">⌘K</kbd>
          </button>
          <a href="#/talk/buyer" className="btn btn--accent" style={{display: "inline-flex"}}>
            Talk to us <span className="arrow">→</span>
          </a>
          <button className="nav-toggle" onClick={onMobileOpen} aria-label="Open menu">
            <MenuIcon />
          </button>
        </div>
      </div>
    </nav>
  );
}

function MobileNav({ open, onClose }) {
  return (
    <div className={"mobile-nav" + (open ? " is-open" : "")} role="dialog" aria-modal="true" aria-label="Menu">
      <div className="mobile-nav__top">
        <Brand small />
        <button className="btn btn--ghost" onClick={onClose} aria-label="Close menu">Close</button>
      </div>
      <ul className="mobile-nav__list">
        {window.SARPAH_PRIMARY_NAV.map(item => (
          <li key={item.slug}>
            <a href={"#" + item.slug} onClick={onClose}>
              <span>{item.label}</span>
              <span className="arrow">→</span>
            </a>
          </li>
        ))}
      </ul>
      <div style={{marginTop: 32}}>
        <a href="#/talk/buyer" onClick={onClose} className="btn btn--accent btn--lg">Talk to us</a>
      </div>
    </div>
  );
}

function Footer() {
  const productGroups = ["Fertilizers", "Grain", "Edible Oils", "Food", "Petroleum", "Timber"];
  const corridors = routesByGroup("Corridors");
  const compliance = routesByGroup("Compliance").slice(0, 8);
  return (
    <footer className="site-footer no-print" role="contentinfo">
      <div className="container-wide">
        <div className="site-footer__top">
          <div className="footer-brand">
            <div className="display" style={{fontSize: "var(--t-3xl)", marginBottom: 4}}>Sarpah</div>
            <div style={{fontFamily:"var(--mono)", fontSize:11, letterSpacing:"0.16em", textTransform:"uppercase", color:"var(--ink-3)", marginBottom: 16}}>Freighters &amp; Logistics</div>
            <p>Mandated origination agent for Russia–CIS commodities, channelling cargoes to East African institutional buyers.</p>
          </div>
          <div className="footer-col">
            <h4>Audiences</h4>
            <ul>
              <li><a href="#/buyer-process">Buyers</a></li>
              <li><a href="#/originators">Originators</a></li>
              <li><a href="#/sub-agents">Sub-agents</a></li>
              <li><a href="#/about">About</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Products</h4>
            <ul>
              {productGroups.map(g => {
                const root = window.SARPAH_ROUTES.find(r => r.group === g && (r.order === 0 || /products\/[^/]+$/.test(r.slug)));
                if (!root) return null;
                return <li key={g}><a href={"#" + root.slug}>{g}</a></li>;
              })}
            </ul>
          </div>
          <div className="footer-col">
            <h4>Corridors</h4>
            <ul>
              {corridors.filter(r => r.slug !== "/origination").map(r => (
                <li key={r.slug}><a href={"#" + r.slug}>{r.title.replace(" Corridor", "")}</a></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h4>Compliance</h4>
            <ul>
              {compliance.map(r => (
                <li key={r.slug}><a href={"#" + r.slug}>{r.title.split(" — ")[0]}</a></li>
              ))}
              <li><a href="#/compliance">All compliance →</a></li>
            </ul>
          </div>
        </div>
        <div className="site-footer__bottom">
          <span>© 2026 Sarpah Freighters &amp; Logistics Ltd.</span>
          <span><a href="#/about">About</a> · <a href="#/buyer-process">Buyers</a> · <a href="#/originators">Originators</a></span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   Icons
   ============================================================ */

function SearchIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
      <circle cx="7" cy="7" r="4.5" />
      <path d="M10.5 10.5L13.5 13.5" strokeLinecap="round" />
    </svg>
  );
}
function MenuIcon() {
  return (
    <svg width="18" height="14" viewBox="0 0 18 14" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <line x1="0" y1="2" x2="18" y2="2"/>
      <line x1="0" y1="12" x2="18" y2="12"/>
    </svg>
  );
}
function Arrow() { return <span className="arrow" aria-hidden="true">→</span>; }
function NorthEast() { return <span className="arrow" aria-hidden="true">↗</span>; }

/* ============================================================
   Search
   ============================================================ */

function SearchModal({ open, onClose }) {
  const [q, setQ] = useState("");
  const [active, setActive] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) {
      setQ(""); setActive(0);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) {
      // top suggestions when empty
      const groups = ["Compliance", "Fertilizers", "Grain", "Corridors", "Insights"];
      return groups.flatMap(g =>
        window.SARPAH_ROUTES.filter(r => r.group === g).slice(0, 2)
      ).slice(0, 8);
    }
    const score = (r) => {
      const hay = `${r.title} ${r.description} ${r.group} ${r.section}`.toLowerCase();
      if (!hay.includes(term)) return 0;
      let s = 1;
      if (r.title.toLowerCase().includes(term)) s += 5;
      if (r.title.toLowerCase().startsWith(term)) s += 4;
      if (r.group.toLowerCase().includes(term)) s += 1;
      return s;
    };
    return window.SARPAH_ROUTES
      .map(r => ({ r, s: score(r) }))
      .filter(x => x.s > 0)
      .sort((a, b) => b.s - a.s)
      .slice(0, 12)
      .map(x => x.r);
  }, [q]);

  useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowDown") { e.preventDefault(); setActive(i => Math.min(i + 1, results.length - 1)); }
      else if (e.key === "ArrowUp")   { e.preventDefault(); setActive(i => Math.max(i - 1, 0)); }
      else if (e.key === "Enter") {
        const r = results[active];
        if (r) { navigate(r.slug); onClose(); }
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, results, active, onClose]);

  if (!open) return null;
  return (
    <div className="search-overlay is-open" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="search-modal" role="dialog" aria-label="Search">
        <div className="search-modal__input-wrap">
          <SearchIcon />
          <input
            ref={inputRef}
            className="search-modal__input"
            placeholder="Search products, compliance, corridors, insights…"
            value={q} onChange={e => { setQ(e.target.value); setActive(0); }}
          />
          <span className="search-modal__hint">{results.length} results</span>
        </div>
        {results.length === 0 ? (
          <div className="search-empty">No matches. Try “urea”, “mombasa”, “KEBS”, “bid bond”.</div>
        ) : (
          <ul className="search-results">
            {results.map((r, i) => (
              <li key={r.slug} className={i === active ? "is-active" : ""} onMouseEnter={() => setActive(i)}>
                <a href={"#" + r.slug} onClick={onClose}>
                  <div>
                    <div className="res-title">{r.title}</div>
                    <div className="res-desc">{r.description}</div>
                  </div>
                  <div className="res-section">{r.group}</div>
                </a>
              </li>
            ))}
          </ul>
        )}
        <div className="search-modal__foot">
          <span><kbd>↑↓</kbd> navigate</span>
          <span><kbd>↵</kbd> open</span>
          <span><kbd>Esc</kbd> close</span>
        </div>
      </div>
    </div>
  );
}

window.Sarpah = window.Sarpah || {};
Object.assign(window.Sarpah, {
  useRoute, navigate, findRoute, routesBySection, routesByGroup,
  useMarkdown, Brand, TopNav, MobileNav, Footer, SearchModal,
  Arrow, NorthEast, SearchIcon,
});
