// TerraGenie Support — components
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// —————————————————— Icon system ——————————————————
const Icons = {
  // UI icons used inline with ui-refs
  dxf: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><text x="12" y="18" fontSize="6" textAnchor="middle" fill="currentColor" stroke="none" fontWeight="700">DXF</text></svg>,
  save: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v6m0 0l-3-3m3 3l3-3" /><circle cx="12" cy="15" r="4" /><path d="M4 20h16" /></svg>,
  location: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="2" fill="currentColor" /><path d="M12 2v4M12 18v4M2 12h4M18 12h4" /></svg>,
  query: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m16 16 5 5" /><path d="M8 11h6M11 8v6" /></svg>,
  stakeout: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v4M12 18v4M2 12h4M18 12h4" /><circle cx="12" cy="12" r="3" /><path d="m8 8 8 8M16 8l-8 8" opacity="0.3" /></svg>,
  select: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4l7 16 2-7 7-2z" /></svg>,
  layers: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 2 10 5-10 5-10-5 10-5z" /><path d="m2 17 10 5 10-5M2 12l10 5 10-5" /></svg>,
  zoom: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m16 16 5 5M8 11h6" /></svg>,
  draw: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75z" /><path d="m14.06 6.19 3.75 3.75" /></svg>,
  undo: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7v6h6" /><path d="M3 13a9 9 0 1 0 3-7.7L3 8" /></svg>,
  dropdown: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="12" rx="2" /><path d="m9 11 3 3 3-3" /></svg>,
  user: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></svg>,
  refresh: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 0 1-15.5 6.3L3 16M3 12a9 9 0 0 1 15.5-6.3L21 8" /><path d="M21 3v5h-5M3 21v-5h5" /></svg>,
  web: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10M12 2a15.3 15.3 0 0 0-4 10 15.3 15.3 0 0 0 4 10" /></svg>,

  // Section icons
  box: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m21 8-9-5-9 5 9 5 9-5z" /><path d="m3 8v8l9 5 9-5V8" /><path d="M12 13v8" /></svg>,
  power: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v10" /><path d="M18.4 6.6a9 9 0 1 1-12.8 0" /></svg>,
  map: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 3 2 6v15l7-3 6 3 7-3V3l-7 3z" /><path d="M9 3v15M15 6v15" /></svg>,
  upload: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></svg>,
  target: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" fill="currentColor" /></svg>,
  pin: () => <svg viewBox="0 0 24 24" 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="3" /></svg>,
  line: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="5" cy="19" r="2" /><circle cx="19" cy="5" r="2" /><path d="m6.5 17.5 11-11" /></svg>,
  polygon: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 2 9 7-4 11H7L3 9z" /></svg>,
  export: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" /></svg>,
  report: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="9" y1="13" x2="15" y2="13" /><line x1="9" y1="17" x2="15" y2="17" /></svg>,
  csv: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><text x="12" y="18" fontSize="5.5" textAnchor="middle" fill="currentColor" stroke="none" fontWeight="700">CSV</text></svg>,

  // Kit icons
  antenna: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12a7 7 0 0 1 14 0" /><path d="M8 12a4 4 0 0 1 8 0" /><circle cx="12" cy="12" r="1.5" fill="currentColor" /><path d="M12 14v8" /></svg>,
  tablet: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="2" width="16" height="20" rx="2" /><line x1="12" y1="18" x2="12" y2="18.01" /></svg>,
  pole: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v20" /><path d="M9 6h6M9 12h6M9 18h6" /></svg>,
  charger: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2 3 14h9l-1 8 10-12h-9z" /></svg>,
  bracket: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="8" width="14" height="10" rx="1" /><path d="M9 8V5a3 3 0 0 1 6 0v3" /></svg>
};

const Icon = ({ name }) => {
  const Cmp = Icons[name];
  return Cmp ? <Cmp /> : null;
};

// —————————————————— Highlighting helper ——————————————————
function highlight(text, query) {
  if (!query || !text) return text;
  const re = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  const parts = String(text).split(re);
  return parts.map((p, i) =>
  re.test(p) ? <mark key={i} className="highlight-match">{p}</mark> : <React.Fragment key={i}>{p}</React.Fragment>
  );
}

// —————————————————— Nav ——————————————————
function SupNav() {
  return (
    <nav className="nav nav-standalone">
      <div className="nav-inner">
        <a href="#" className="nav-brand" onClick={(e) => e.preventDefault()}><img src="assets/logos/wordmark-light.png" className="nav-logo" alt="TerraGenie" /></a>
      </div>
    </nav>);

}

// —————————————————— Hero ——————————————————
function SupHero({ query, setQuery, stats }) {
  return (
    <header className="sup-hero">
      <div className="sup-hero-inner">
        <div className="sup-eyebrow"><span className="dot"></span>TerraGenie Operator's Manual · 2026 Edition</div>
        <h1 className="sup-title">Support &amp; <em>How-To</em></h1>
        <p className="sup-lede">Every step, every button, every gotcha — searchable.</p>
        <div className="sup-search">
          <svg className="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
          <input
            type="text"
            placeholder="Search guides, steps, icons... (e.g. 'stakeout', 'DXF', 'blue dot')"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            autoComplete="off"
            spellCheck="false" />
          
          <span className="kbd">{query ? `${stats.matched} match${stats.matched === 1 ? '' : 'es'}` : `${stats.total} topics`}</span>
        </div>
      </div>
    </header>);

}

// —————————————————— Step content renderer ——————————————————
function renderInline(item, query) {
  if (item.kind === "li") {
    return <li>{highlight(item.text, query)}</li>;
  }
  if (item.kind === "li-ui") {
    return (
      <li>
        {highlight(item.text, query)}
        <span className="ui-ref"><span className="ui-icon"><Icon name={item.ref.icon} /></span>{item.ref.text}</span>
        {item.suffix && highlight(item.suffix, query)}
      </li>);

  }
  return null;
}

// —————————————————— Annotated interface map ——————————————————
function IfaceAnnotated({ data, query }) {
  const [active, setActive] = useState(1);
  const row = data.rows.find((r) => r.n === active) || data.rows[0];
  return (
    <div className="iface-annot">
      <div className="iface-annot-stage">
        <img src={data.image} alt="TerraGenie app interface" className="iface-annot-img" loading="lazy" />
        <div className="iface-annot-overlay">
          {data.rows.map((r) =>
          <button
            key={r.n}
            className={"iface-pin" + (active === r.n ? " is-active" : "")}
            style={{ left: r.x + "%", top: r.y + "%" }}
            onClick={() => setActive(r.n)}
            onMouseEnter={() => setActive(r.n)}
            aria-label={r.title}>
            
              {r.n}
            </button>
          )}
        </div>
      </div>
      <div className="iface-annot-side">
        <div className="iface-annot-current">
          <div className="iac-num">{String(row.n).padStart(2, "0")}</div>
          <div className="iac-icon"><Icon name={row.icon} /></div>
          <div className="iac-text">
            <b>{highlight(row.title, query)}</b>
            <em>{highlight(row.desc, query)}</em>
          </div>
        </div>
        <div className="iface-annot-legend">
          {data.rows.map((r) =>
          <button
            key={r.n}
            className={"iac-legend-row" + (active === r.n ? " is-active" : "")}
            onClick={() => setActive(r.n)}
            onMouseEnter={() => setActive(r.n)}>
            
              <span className="iac-legend-num">{r.n}</span>
              <span className="iac-legend-icon"><Icon name={r.icon} /></span>
              <span className="iac-legend-title">{highlight(r.title, query)}</span>
            </button>
          )}
        </div>
      </div>
    </div>);

}

function SectionContent({ content, query }) {
  return (
    <>
      {content.map((c, i) => {
        if (c.kind === "p") return <p key={i} style={{ fontSize: 15, lineHeight: 1.65, color: "var(--fg-2)", margin: "0 0 14px" }}>{highlight(c.text, query)}</p>;
        if (c.kind === "h4") return <h4 key={i} style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 17, color: "var(--tg-ink)", letterSpacing: "-0.01em", margin: "24px 0 10px", paddingTop: 14, borderTop: "1px solid var(--border-1)" }}>{highlight(c.text, query)}</h4>;
        if (c.kind === "p-ul") return (
          <ul key={i} style={{ listStyle: "none", padding: 0, margin: "10px 0 14px", display: "flex", flexDirection: "column", gap: 6 }}>
            {c.items.map((it, ix) =>
            <li key={ix} style={{ fontSize: 15, color: "var(--fg-2)", lineHeight: 1.55, paddingLeft: 22, position: "relative" }}>
                <span style={{ position: "absolute", left: 6, top: 10, width: 6, height: 6, borderRadius: "50%", background: "var(--tg-red)" }} />{highlight(it, query)}
              </li>
            )}
          </ul>);

        if (c.kind === "step") return (
          <div key={i} className="step-block">
            <div className="step-num">{c.n}</div>
            <div className="step-body">
              <h4>{highlight(c.title, query)}</h4>
              <ul>{c.body.map((b, bi) => <React.Fragment key={bi}>{renderInline(b, query)}</React.Fragment>)}</ul>
            </div>
          </div>);

        if (c.kind === "callout") {
          const icons = { tip: "💡", warn: "⚠", note: "📌", success: "✅" };
          return (
            <div key={i} className={"callout callout-" + c.variant}>
              <div className="callout-icon">{icons[c.variant]}</div>
              <div>
                <strong>{highlight(c.title, query)}</strong>
                {highlight(c.body, query)}
              </div>
            </div>);

        }
        if (c.kind === "status") return (
          <div key={i} className="status-grid">
            {c.rows.map((r, ri) =>
            <div key={ri} className="status-row">
                <div className={"status-dot " + r.dot}>{r.dot === "blue-x" ? "✕" : ""}</div>
                <div><b>{highlight(r.title, query)}</b> <em>{highlight(r.desc, query)}</em></div>
              </div>
            )}
          </div>);

        if (c.kind === "kit") return (
          <div key={i} className="kit-grid">
            {c.items.map((k, ki) =>
            <div key={ki} className="kit-item">
                <div className="icon"><Icon name={k.icon} /></div>
                <div className="label">{highlight(k.label, query)}</div>
              </div>
            )}
          </div>);

        if (c.kind === "iface") return (
          <div key={i} className="iface-map">
            {c.rows.map((r, ri) =>
            <div key={ri} className="iface-row">
                <div className="iface-icon"><Icon name={r.icon} /></div>
                <div className="iface-text"><b>{highlight(r.title, query)}</b><em>{highlight(r.desc, query)}</em></div>
              </div>
            )}
          </div>);

        if (c.kind === "iface-annotated") return <IfaceAnnotated key={i} data={c} query={query} />;
        return null;
      })}
    </>);

}

// —————————————————— Topic card (grid tile) ——————————————————
function SupCard({ section, onOpen, query, idx }) {
  return (
    <button
      className="sup-card"
      onClick={() => onOpen(section.id)}
      style={{ animationDelay: idx * 35 + "ms" }}
      aria-label={"Open " + section.title}>
      
      <div className="sup-card-icon"><Icon name={section.icon} /></div>
      <div className="sup-card-meta">{section.category} · {section.num}</div>
      <h3 className="sup-card-title">{highlight(section.title, query)}</h3>
      <div className="sup-card-sub">{highlight(section.sub, query)}</div>
      <div className="sup-card-foot">
        <span className="sup-card-cta">Read guide</span>
        <span className="sup-card-arrow" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
        </span>
      </div>
    </button>);

}

// —————————————————— Modal popup for full guide content ——————————————————
function SupModal({ section, onClose, query }) {
  const modalRef = useRef(null);
  const [closing, setClosing] = useState(false);

  const requestClose = useCallback(() => {
    setClosing(true);
    setTimeout(onClose, 220);
  }, [onClose]);

  useEffect(() => {
    const onKey = (e) => {if (e.key === "Escape") requestClose();};
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    // Focus the modal shell for screen readers
    setTimeout(() => modalRef.current && modalRef.current.focus(), 20);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [requestClose]);

  if (!section) return null;

  return (
    <div className={"sup-modal-scrim" + (closing ? " is-closing" : "")} onClick={requestClose}>
      <div
        ref={modalRef}
        tabIndex={-1}
        className={"sup-modal" + (closing ? " is-closing" : "")}
        role="dialog"
        aria-modal="true"
        aria-labelledby="sup-modal-title"
        onClick={(e) => e.stopPropagation()}>
        
        <button className="sup-modal-close" onClick={requestClose} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>
        <header className="sup-modal-head">
          <div className="sup-modal-icon"><Icon name={section.icon} /></div>
          <div className="sup-modal-heads">
            <div className="sup-modal-eyebrow">{section.category} · {section.num}</div>
            <h2 id="sup-modal-title" className="sup-modal-title">{section.title}</h2>
            <p className="sup-modal-sub">{section.sub}</p>
          </div>
        </header>
        <div className="sup-modal-body">
          <SectionContent content={section.content} query={query} />
          {section.video &&
          <div className="video-block">
              <div className="video-label"><span className="rec-dot"></span>Watch: {section.title}</div>
              <video src={section.video} controls playsInline preload="metadata" />
            </div>
          }
        </div>
      </div>
    </div>);

}

// —————————————————— Contact block + ticket form ——————————————————
function SupContact() {
  useEffect(() => {
    if (document.querySelector('script[data-ghl-form-embed]')) return;
    const s = document.createElement('script');
    s.src = 'https://link.msgsndr.com/js/form_embed.js';
    s.async = true;
    s.setAttribute('data-ghl-form-embed', '');
    document.body.appendChild(s);
  }, []);
  return (
    <section className="sup-contact">
      <div className="container sup-contact-inner">
        <div>
          <div className="sup-eyebrow"><span className="dot"></span>Still stuck? We've got you.</div>
          <h2>Real humans. <em>US-based.</em> No phone trees.</h2>
          <p>If the guides above didn't cover it, reach a TerraGenie specialist directly. Every ticket is answered by someone who has run the TG2 on a jobsite.</p>
          <div className="channel-list">
            <a href="tel:+17277583772" className="channel">
              <div className="ch-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" /></svg>
              </div>
              <div className="ch-meta" style={{ fontSize: "18px" }}><b style={{ fontSize: "18px" }}>Call support</b><span>(727) 758-3772   ·   Mon–Fri 8a–6p ET</span></div>
              <div className="ch-arrow">→</div>
            </a>
            <a href="mailto:support@terragenie.us" className="channel">
              <div className="ch-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-10 7L2 7" /></svg>
              </div>
              <div className="ch-meta"><b style={{ fontSize: "18px" }}>Email support</b><span style={{ fontSize: "18px" }}>support@terragenie.us</span></div>
              <div className="ch-arrow">→</div>
            </a>
          </div>
        </div>
        <div className="ticket-form ticket-form--ghl">
          <iframe
            src="https://api.leadconnectorhq.com/widget/form/f4iifg5Pq9Zu0WaCowlC"
            style={{ width: "100%", height: "640px", border: "none", background: "transparent" }}
            id="inline-f4iifg5Pq9Zu0WaCowlC"
            data-layout="{'id':'INLINE'}"
            data-trigger-type="alwaysShow"
            data-trigger-value=""
            data-activation-type="alwaysActivated"
            data-activation-value=""
            data-deactivation-type="neverDeactivate"
            data-deactivation-value=""
            data-form-name="Issue Ticket Form"
            data-height="685"
            data-layout-iframe-id="inline-f4iifg5Pq9Zu0WaCowlC"
            data-form-id="f4iifg5Pq9Zu0WaCowlC"
            title="Issue Ticket Form" />
        </div>
      </div>
    </section>);

}

// —————————————————— App root ——————————————————
function SupApp() {
  const [query, setQuery] = useState("");
  const [openId, setOpenId] = useState(null);

  const q = query.trim().toLowerCase();
  const filtered = useMemo(() => {
    if (!q) return SUPPORT_SECTIONS;
    return SUPPORT_SECTIONS.filter((s) => {
      const blob = [s.title, s.sub, s.category, s.keywords, JSON.stringify(s.content)].join(" ").toLowerCase();
      return blob.includes(q);
    });
  }, [q]);

  // Group by category (preserving first-seen order)
  const groups = useMemo(() => {
    const order = [];
    const bucket = {};
    for (const s of filtered) {
      if (!bucket[s.category]) {bucket[s.category] = [];order.push(s.category);}
      bucket[s.category].push(s);
    }
    return order.map((cat) => ({ cat, items: bucket[cat] }));
  }, [filtered]);

  const activeSection = openId ? SUPPORT_SECTIONS.find((s) => s.id === openId) : null;

  // Deep-link support: open the modal if URL hash matches a section id
  useEffect(() => {
    const applyHash = () => {
      const id = (window.location.hash || "").replace(/^#/, "");
      const hit = SUPPORT_SECTIONS.find((s) => s.id === id);
      if (hit) setOpenId(hit.id);
    };
    applyHash();
    window.addEventListener("hashchange", applyHash);
    return () => window.removeEventListener("hashchange", applyHash);
  }, []);

  return (
    <>
      <SupNav />
      <SupHero query={query} setQuery={setQuery} stats={{ matched: filtered.length, total: SUPPORT_SECTIONS.length }} />
      <section className="sup-main">
        <div className="container">
          {filtered.length === 0 ?
          <div className="no-results">
              <div className="big">No results for "{query}"</div>
              <p>Try a different keyword, or scroll down to open a ticket with support.</p>
            </div> :

          <div className="sup-groups">
              {groups.map((g, gi) =>
            <section key={g.cat} className="sup-group" style={{ animationDelay: gi * 70 + "ms", opacity: 1 }}>
                  <header className="sup-group-head">
                    <h2 className="sup-group-title">{g.cat}</h2>
                    <div className="sup-group-meta">
                      <span>{g.items.length} guide{g.items.length === 1 ? "" : "s"}</span>
                      <span className="sup-group-rule" aria-hidden="true" />
                    </div>
                  </header>
                  <div className="sup-card-grid">
                    {g.items.map((s, i) =>
                <SupCard key={s.id} section={s} onOpen={setOpenId} query={q} idx={i} />
                )}
                  </div>
                </section>
            )}
            </div>
          }
        </div>
      </section>
      {activeSection &&
      <SupModal
        section={activeSection}
        query={q}
        onClose={() => {
          setOpenId(null);
          if (window.location.hash) {
            history.replaceState(null, "", window.location.pathname + window.location.search);
          }
        }} />

      }
      <SupContact />
      <footer className="footer">
        <div className="footer-bottom" style={{ paddingTop: 32 }}>
          <div className="footer-disclaimer">
            TerraGenie is a tool for estimation, construction layout, and reference only. It does not replace the services of a Professional Land Surveyor (PLS) or professional licensure. Always consult a licensed professional for boundary determination and legal certification.
          </div>
          <div className="footer-meta">
            <span>© 2026 Dimensional Perception Technology US Inc.</span>
            <a href="TerraGenie Homepage.html#"></a>
            <a href="TerraGenie Homepage.html#"></a>
          </div>
        </div>
      </footer>
    </>);

}

Object.assign(window, { SupApp });