// app.jsx — Shell: header, footer, router, tweaks

const { useEffect: useEff, useState: useStateApp } = React;

const NAV = [
  { id: "home", label: "Home" },
  { id: "about", label: "About" },
  { id: "people", label: "People" },
  { id: "services", label: "Services" },
  { id: "assignments", label: "Assignments" },
  { id: "articles", label: "Articles" },
  { id: "careers", label: "Careers" },
  { id: "icai", label: "ICAI" },
];

function CAIcon() {
  return <img src="assets/icai-logo/ca-india-logo.png" alt="ICAI CA India logo" />;
}

function UtilBar() {
  return (
    <div className="util-bar">
      <div className="container">
        <div className="util-bar__row">
          <div className="util-bar__group">
            <a href="tel:+919342611390" aria-label="Call CA. Rajesh Bagrecha">
              <span>+91 93426 11390</span>
            </a>
            <span className="util-bar__sep">|</span>
            <a href="mailto:rajeshbagrecha@hotmail.com">rajeshbagrecha@hotmail.com</a>
          </div>
          <div className="util-bar__group">
            <span>Mon–Sat · 10:00–19:00 IST</span>
            <span className="util-bar__sep">|</span>
            <span className="util-bar__frn">FRN&nbsp;<b>006339S/S000238</b></span>
          </div>
        </div>
      </div>
    </div>
  );
}

function Header({ page, goto }) {
  const [drawerOpen, setDrawerOpen] = useStateApp(false);
  const activeId = page.startsWith("partner-") ? "people" : (page === "employees" ? "people" : (page === "contact" ? null : page));
  return (
    <>
      <div className="tricolor-rule" aria-hidden="true">
        <span /><span /><span />
      </div>
      <UtilBar />
      <header className="header">
        <div className="container">
          <div className="header__row">
            <button className="header__mark" onClick={() => goto("home")} style={{ background: "transparent", border: 0, padding: 0, cursor: "pointer", textAlign: "left", fontFamily: "inherit", color: "inherit" }}>
              <CAIcon />
              <span className="header__mark-text">
                <span className="header__name">Bagrecha &amp; Singhvi LLP</span>
                <span className="header__sub">Chartered Accountants · <span className="mono">FRN 006339S/S000238</span></span>
              </span>
            </button>
            <nav className="nav" aria-label="Primary">
              {NAV.concat([{id:"contact", label:"Contact"}]).map(n => (
                <button key={n.id}
                  className={`nav__link ${(activeId === n.id) || (page === "contact" && n.id === "contact") ? "is-active" : ""}`}
                  onClick={() => goto(n.id)}>
                  {n.label}
                </button>
              ))}
            </nav>
            <button className="header__menu-btn" onClick={() => setDrawerOpen(true)}>Menu</button>
          </div>
        </div>
      </header>

      <div className="drawer" data-open={drawerOpen}>
        <div className="container">
          <div className="drawer__head">
            <span className="header__name">{FIRM.name}</span>
            <button className="header__menu-btn" onClick={() => setDrawerOpen(false)}>Close</button>
          </div>
          <ul>
            {NAV.concat([{id:"contact", label:"Contact"}]).map(n => (
              <li key={n.id}><button onClick={() => { setDrawerOpen(false); goto(n.id); }}>{n.label}</button></li>
            ))}
          </ul>
        </div>
      </div>
    </>
  );
}

function Footer({ goto }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__top">
          <div>
            <div className="footer__mark">
              <CAIcon />
              <div>
                <div className="footer__name">Bagrecha &amp; Singhvi LLP</div>
                <div className="footer__designation">Chartered Accountants</div>
              </div>
            </div>
            <p className="footer__meta">FRN <b>006339S/S000238</b> · ICAI MRN 207484, 027197</p>
            <p className="footer__meta">Established 1993 · Ballari · Bengaluru</p>
            <p className="footer__meta" style={{ marginTop: 14 }}>
              <a href="https://www.linkedin.com/in/bagrecha-and-singhvi-0ab804222/" target="_blank" rel="noopener">LinkedIn — firm profile ↗</a>
            </p>
          </div>
          <div>
            <h4>Firm</h4>
            <ul>
              <li><button onClick={() => goto("about")}>About</button></li>
              <li><button onClick={() => goto("people")}>People</button></li>
              <li><button onClick={() => goto("contact")}>Contact</button></li>
            </ul>
          </div>
          <div>
            <h4>Practice</h4>
            <ul>
              <li><button onClick={() => goto("services")}>All practice areas</button></li>
              <li><button onClick={() => goto("assignments")}>Assignments</button></li>
              <li><button onClick={() => goto("articles")}>Articles &amp; updates</button></li>
              <li><button onClick={() => goto("careers")}>Careers &amp; articleship</button></li>
            </ul>
          </div>
          <div>
            <h4>Partners</h4>
            <ul>
              <li><button onClick={() => goto("partner-rajesh-bagrecha")}>CA. Rajesh Bagrecha</button></li>
              <li><button onClick={() => goto("partner-surendraa-singhvii")}>CA. Surendraa Singhvii</button></li>
              <li><button onClick={() => goto("icai")}>ICAI &amp; regulatory links</button></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <p style={{ margin: 0 }}>
            <span className="tricolor" aria-hidden="true"><span /><span /><span /></span>
            © 1993–2026 Bagrecha &amp; Singhvi LLP. All rights reserved.
          </p>
          <p style={{ margin: 0, maxWidth: "56ch", textAlign: "right" }}>
            Maintained as a passive reference per ICAI Council Advisory M-626/14/2020 and the ICAI Code of Ethics, 13th edition.
          </p>
        </div>
      </div>
    </footer>
  );
}

// ===== Tweaks =====
function BNSTweaks({ t, setTweak }) {
  // apply tweaks to <html>
  useEff(() => {
    const html = document.documentElement;
    html.setAttribute("data-theme", t.theme);
    html.setAttribute("data-density", t.density);
    html.setAttribute("data-display", t.display);
    // accent hue swap — only in paper / sepia (charcoal has its own warm accent)
    if (t.theme !== "charcoal") {
      html.style.setProperty("--accent",      `oklch(0.42 0.08 ${t.accentHue})`);
      html.style.setProperty("--accent-soft", `oklch(0.42 0.08 ${t.accentHue} / 0.10)`);
      html.style.setProperty("--accent-rule", `oklch(0.42 0.08 ${t.accentHue} / 0.30)`);
    } else {
      html.style.removeProperty("--accent");
      html.style.removeProperty("--accent-soft");
      html.style.removeProperty("--accent-rule");
    }
  }, [t.theme, t.density, t.display, t.accentHue]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Surface">
        <TweakRadio label="Theme" value={t.theme} options={[
          {value:"paper", label:"Paper"},
          {value:"sepia", label:"Sepia"},
          {value:"charcoal", label:"Ink"},
        ]} onChange={v => setTweak("theme", v)} />
        <TweakRadio label="Density" value={t.density} options={[
          {value:"comfortable", label:"Comfortable"},
          {value:"compact", label:"Compact"},
        ]} onChange={v => setTweak("density", v)} />
      </TweakSection>
      <TweakSection label="Typography">
        <TweakRadio label="Headings" value={t.display} options={[
          {value:"serif", label:"Serif"},
          {value:"sans", label:"Sans"},
        ]} onChange={v => setTweak("display", v)} />
      </TweakSection>
      <TweakSection label="Accent (Paper / Sepia)">
        <TweakColor label="Hue"
          value={`oklch(0.42 0.08 ${t.accentHue})`}
          options={[
            "oklch(0.42 0.08 250)",
            "oklch(0.42 0.08 30)",
            "oklch(0.42 0.08 150)",
            "oklch(0.42 0.08 320)",
          ]}
          onChange={c => {
            const m = c.match(/oklch\([^)]*\s(\d+(?:\.\d+)?)\)/);
            if (m) setTweak("accentHue", parseFloat(m[1]));
          }}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ===== Router =====

const PAGE_LABELS = {
  home: "Home", about: "About", people: "People",
  employees: "Members at the firm", services: "Services",
  assignments: "Assignments", articles: "Articles", careers: "Careers",
  icai: "ICAI", contact: "Contact",
};

function App() {
  const [page, setPage] = useStateApp(() => {
    const hash = (window.location.hash || "").replace("#", "");
    return hash || "home";
  });
  const [t, setT] = useStateApp(() => window.__TWEAK_DEFAULTS || { theme: "paper", density: "comfortable", display: "serif", accentHue: 250 });

  const setTweak = (k, v) => {
    if (typeof k === "object") {
      setT(prev => ({ ...prev, ...k }));
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: k }, "*");
    } else {
      setT(prev => ({ ...prev, [k]: v }));
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
    }
  };

  const goto = (id) => {
    setPage(id);
    window.location.hash = id;
    // scroll to top of content after a tick
    setTimeout(() => window.scrollTo({ top: 0, behavior: "smooth" }), 30);
  };
  useEff(() => { window.__goto = goto; }, []);

  useEff(() => {
    const onHash = () => {
      const h = (window.location.hash || "").replace("#", "") || "home";
      setPage(h);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  let body;
  if (page === "home") body = <PageHome />;
  else if (page === "about") body = <PageAbout />;
  else if (page === "people") body = <PagePeople />;
  else if (page === "employees") body = <PageEmployees />;
  else if (page.startsWith("partner-")) body = <PagePartner slug={page.slice("partner-".length)} />;
  else if (page === "services") body = <PageServices />;
  else if (page === "assignments") body = <PageAssignments />;
  else if (page === "articles") body = <PageArticles />;
  else if (page.startsWith("article-")) body = <PageArticle slug={page.slice("article-".length)} />;
  else if (page === "careers") body = <PageCareers />;
  else if (page === "icai") body = <PageICAI />;
  else if (page === "contact") body = <PageContact />;
  else body = <PageHome />;

  return (
    <>
      <Header page={page} goto={goto} />
      <main data-screen-label={`${PAGE_LABELS[page] || page}`}>
        {body}
      </main>
      <Footer goto={goto} />
      <BNSTweaks t={t} setTweak={setTweak} />
    </>
  );
}

// Mount when both pages.jsx and pages2.jsx have loaded.
// (Babel transpiles scripts in document order, so by the time this runs, the others are ready.)
// We also wait for tweaks-panel to expose TweaksPanel.
function mount() {
  if (!window.PageHome || !window.PagePeople || !window.TweaksPanel) {
    setTimeout(mount, 30); return;
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
}
mount();
