// SPA shell — sidebar nav, hash routing, tweaks integration
const { useState, useEffect, useMemo, useRef } = React;

const NAV = [
  { group: "Start", items: [
    { id: "overview", label: "Overview", page: "OverviewPage" },
  ]},
  { group: "Brand Expression", items: [
    { id: "logo", label: "Logo & Lockups", page: "LogoPage" },
    { id: "color", label: "Color System", page: "ColorPage" },
    { id: "gradient", label: "Gradients", page: "GradientPage" },
    { id: "type", label: "Typography", page: "TypePage" },
    { id: "iconography", label: "Iconography", page: "IconographyPage" },
    { id: "photography", label: "Photography & Duotone", page: "PhotographyPage" },
    { id: "illustrations", label: "Platform Illustrations", page: "PlatformIllustrationsPage" },
    { id: "patterns", label: "Patterns & Textures", page: "PatternPage" },
  ]},
  { group: "Motion", items: [
    { id: "motion-principles", label: "Principles", page: "MotionPrinciplesPage" },
    { id: "motion-timing", label: "Timing & Easing", page: "MotionTimingPage" },
    { id: "motion-demos", label: "Live Demos", page: "MotionDemosPage" },
  ]},
  { group: "Voice", items: [
    { id: "voice", label: "Voice & Tone", page: "VoicePage" },
    { id: "donts", label: "Do's & Don'ts", page: "DontsPage" },
  ]},
  { group: "Reference", items: [
    { id: "templates", label: "Campaign Surfaces", page: "TemplatesPage" },
    { id: "campaign-lp", label: "Webinar Landing Page", page: "CampaignLandingPage" },
    { id: "campaign-ads", label: "HTML5 Ad Set", page: "CampaignAdsPage" },
    { id: "onepager", label: "One-Pager", page: "OnePagerPage" },
    { id: "solution-brief", label: "Solution Brief", page: "SolutionBriefPage" },
    { id: "sources", label: "Sources & Provenance", page: "SourcesPage" },
  ]},
];

const FLAT_NAV = NAV.flatMap(g => g.items);

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryColor": "#2E3091",
  "accentColor": "#29ABE3",
  "actionColor": "#F25924",
  "fontDisplay": "Montserrat",
  "density": "comfortable",
  "darkSidebar": true
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = useState(() => (location.hash.replace("#", "") || "overview"));
  const [search, setSearch] = useState("");
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, ()=>{}];
  const mainRef = useRef(null);

  useEffect(() => {
    const onHash = () => setRoute(location.hash.replace("#", "") || "overview");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffect(() => {
    if (mainRef.current) mainRef.current.scrollTop = 0;
  }, [route]);

  // Apply tweaks live to CSS vars
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--rs-indigo", tweaks.primaryColor);
    root.style.setProperty("--rs-cyan", tweaks.accentColor);
    root.style.setProperty("--rs-orange", tweaks.actionColor);
    root.style.setProperty("--rs-grad-hero", `linear-gradient(180deg, ${tweaks.primaryColor} 16%, ${tweaks.accentColor} 62%)`);
    root.style.setProperty("--rs-font-display", `"${tweaks.fontDisplay}", sans-serif`);
    root.dataset.density = tweaks.density;
    root.dataset.sidebar = tweaks.darkSidebar ? "dark" : "light";
  }, [tweaks]);

  window.RS_NAV = (id) => { location.hash = id; };

  const currentItem = FLAT_NAV.find(i => i.id === route) || FLAT_NAV[0];
  const PageComponent = window[currentItem.page] || window.OverviewPage;

  const filteredNav = useMemo(() => {
    if (!search.trim()) return NAV;
    const q = search.toLowerCase();
    return NAV.map(g => ({
      ...g,
      items: g.items.filter(i => i.label.toLowerCase().includes(q) || g.group.toLowerCase().includes(q))
    })).filter(g => g.items.length);
  }, [search]);

  const idx = FLAT_NAV.findIndex(i => i.id === currentItem.id);
  const prev = idx > 0 ? FLAT_NAV[idx - 1] : null;
  const next = idx < FLAT_NAV.length - 1 ? FLAT_NAV[idx + 1] : null;

  return (
    <div className="app-shell">
      <aside className="sidebar">
        <div className="sb-brand">
          <RegScaleLogo size="sm" inverse={tweaks.darkSidebar} />
          <div className="sb-brand-meta">
            <div className="sb-brand-title">Brand & Motion</div>
            <div className="sb-brand-version">Guidelines · v1.0</div>
          </div>
        </div>
        <div className="sb-search">
          <input
            type="text"
            placeholder="Search guidelines…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
        <nav className="sb-nav">
          {filteredNav.map(g => (
            <div key={g.group} className="sb-group">
              <div className="sb-group-label">{g.group}</div>
              {g.items.map(item => (
                <a
                  key={item.id}
                  href={"#" + item.id}
                  className={"sb-link " + (item.id === currentItem.id ? "active" : "")}
                >
                  {item.label}
                </a>
              ))}
            </div>
          ))}
        </nav>
        <div className="sb-foot">
          <div className="sb-foot-label">For AI agents</div>
          <p>Reference this artifact when generating RegScale campaign assets — landing pages, HTML5 ads, email banners.</p>
        </div>
      </aside>

      <main className="main" ref={mainRef}>
        <div className="main-bar">
          <div className="crumbs">
            <span>RegScale</span>
            <span className="sep">/</span>
            <span>{NAV.find(g => g.items.find(i => i.id === currentItem.id))?.group}</span>
            <span className="sep">/</span>
            <span className="current">{currentItem.label}</span>
          </div>
          <div className="main-bar-actions">
            <a className="bar-link" href="#templates" onClick={(e)=>{e.preventDefault(); window.RS_NAV("templates");}}>Templates</a>
            <button className="bar-cta" onClick={()=>{
              window.parent.postMessage({type: "__edit_mode_available"}, "*");
              alert("Use the Tweaks toggle in the toolbar to customize.");
            }}>Customize</button>
          </div>
        </div>

        <div className="main-content">
          <PageComponent />

          <div className="page-foot">
            {prev ? (
              <a className="page-foot-link prev" href={"#" + prev.id}>
                <div className="dir">← Previous</div>
                <div className="lab">{prev.label}</div>
              </a>
            ) : <div />}
            {next ? (
              <a className="page-foot-link next" href={"#" + next.id}>
                <div className="dir">Next →</div>
                <div className="lab">{next.label}</div>
              </a>
            ) : <div />}
          </div>
        </div>
      </main>

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Color">
            <window.TweakColor label="Primary (Indigo)" value={tweaks.primaryColor} onChange={v => setTweak("primaryColor", v)} />
            <window.TweakColor label="Accent (Cyan)" value={tweaks.accentColor} onChange={v => setTweak("accentColor", v)} />
            <window.TweakColor label="Action (Orange)" value={tweaks.actionColor} onChange={v => setTweak("actionColor", v)} />
          </window.TweakSection>
          <window.TweakSection title="Type">
            <window.TweakSelect
              label="Display font"
              value={tweaks.fontDisplay}
              onChange={v => setTweak("fontDisplay", v)}
              options={[
                { value: "Montserrat", label: "Montserrat (canonical)" },
                { value: "Inter", label: "Inter" },
                { value: "Manrope", label: "Manrope" },
                { value: "Space Grotesk", label: "Space Grotesk" },
              ]}
            />
          </window.TweakSection>
          <window.TweakSection title="Layout">
            <window.TweakRadio
              label="Density"
              value={tweaks.density}
              onChange={v => setTweak("density", v)}
              options={[
                { value: "compact", label: "Compact" },
                { value: "comfortable", label: "Comfortable" },
                { value: "spacious", label: "Spacious" },
              ]}
            />
            <window.TweakToggle
              label="Dark sidebar"
              value={tweaks.darkSidebar}
              onChange={v => setTweak("darkSidebar", v)}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
