// Main app shell: header, footer, router, tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#C8A04A",
  "headlineFont": "Cormorant Garamond",
  "darkHeroes": true
}/*EDITMODE-END*/;

const ROUTES_BY_PAGE = NAV.reduce((acc, item) => {
  acc[item.id] = item.path;
  return acc;
}, {});

const PAGES_BY_ROUTE = NAV.reduce((acc, item) => {
  acc[item.path] = item.id;
  return acc;
}, {});

const LEGAL_NAV = [
  { id: "privacy", label: "Privacy", path: "/privacy" },
  { id: "terms", label: "Terms", path: "/terms" },
  { id: "accessibility", label: "Accessibility", path: "/accessibility" },
];

LEGAL_NAV.forEach(item => {
  ROUTES_BY_PAGE[item.id] = item.path;
  PAGES_BY_ROUTE[item.path] = item.id;
});

ROUTES_BY_PAGE.membershipCard = "/membership-card";
PAGES_BY_ROUTE["/membership-card"] = "membershipCard";

const NEWS_ITEM_ROUTE_PREFIX = "/news/";

const PAGE_TITLES = {
  home: "CAABA — Central Asian American Bar Association",
  about: "About — CAABA",
  leadership: "Leadership — CAABA",
  projects: "Projects — CAABA",
  news: "News — CAABA",
  newsItem: "News — CAABA",
  membership: "Membership — CAABA",
  donate: "Donate — CAABA",
  contact: "Contact — CAABA",
  privacy: "Privacy Policy — CAABA",
  terms: "Terms of Use — CAABA",
  accessibility: "Accessibility — CAABA",
  membershipCard: "Membership Card — CAABA",
  notFound: "Page Not Found — CAABA",
};

const normalizePath = (pathname) => {
  if (!pathname) return "/";
  const trimmed = pathname.replace(/\/+$/, "");
  return trimmed || "/";
};

const getNewsItemIdFromPath = (pathname) => {
  const normalized = normalizePath(pathname);
  if (!normalized.startsWith(NEWS_ITEM_ROUTE_PREFIX)) return null;
  const slug = normalized.slice(NEWS_ITEM_ROUTE_PREFIX.length);
  if (!slug || slug.includes("/")) return null;
  try {
    return decodeURIComponent(slug);
  } catch {
    return slug;
  }
};

const getPageFromPath = (pathname) => {
  const exact = PAGES_BY_ROUTE[normalizePath(pathname)];
  if (exact) return exact;
  if (getNewsItemIdFromPath(pathname)) return "newsItem";
  return "notFound";
};

const isModifiedEvent = (e) => e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0;

const handleInternalNavigation = (e, pageId, navigate) => {
  if (isModifiedEvent(e)) return;
  e.preventDefault();
  navigate(pageId);
};

const App = () => {
  const [page, setPage] = React.useState(() => getPageFromPath(window.location.pathname));
  const [newsItemId, setNewsItemId] = React.useState(() => getNewsItemIdFromPath(window.location.pathname));
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [page, newsItemId]);

  React.useEffect(() => {
    const onPopState = () => {
      setPage(getPageFromPath(window.location.pathname));
      setNewsItemId(getNewsItemIdFromPath(window.location.pathname));
    };
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  React.useEffect(() => {
    document.title = PAGE_TITLES[page] || PAGE_TITLES.notFound;
  }, [page]);

  // Tweak mode protocol
  React.useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  React.useEffect(() => {
    document.documentElement.style.setProperty("--gold", tweaks.accent);
  }, [tweaks.accent]);

  const setTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v }}, "*");
  };

  const navigate = (pageId, { replace = false, id = null } = {}) => {
    let nextPath = null;
    if (pageId === "newsItem" && id) {
      nextPath = `${NEWS_ITEM_ROUTE_PREFIX}${encodeURIComponent(id)}`;
    } else {
      nextPath = ROUTES_BY_PAGE[pageId] || null;
    }

    if (!nextPath) {
      setPage("notFound");
      setNewsItemId(null);
      return;
    }

    const currentPath = normalizePath(window.location.pathname);
    if (currentPath !== nextPath) {
      const method = replace ? "replaceState" : "pushState";
      window.history[method]({}, "", nextPath);
    }

    setPage(pageId);
    setNewsItemId(pageId === "newsItem" ? id : null);
  };

  return (
    <>
      <Header page={page} navigate={navigate}/>
      <main>
        {page === "home" && <HomePage navigate={navigate}/>}
        {page === "about" && <AboutPage navigate={navigate}/>}
        {page === "leadership" && <LeadershipPage navigate={navigate}/>}
        {page === "projects" && <ProjectsPage navigate={navigate}/>}
        {page === "news" && <NewsPage navigate={navigate}/>}
        {page === "newsItem" && <NewsItemPage navigate={navigate} itemId={newsItemId}/>}
        {page === "membership" && <MembershipPage navigate={navigate}/>}
        {page === "donate" && <DonatePage navigate={navigate}/>}
        {page === "contact" && <ContactPage navigate={navigate}/>}
        {page === "privacy" && <PrivacyPage navigate={navigate}/>}
        {page === "terms" && <TermsPage navigate={navigate}/>}
        {page === "accessibility" && <AccessibilityPage navigate={navigate}/>}
        {page === "membershipCard" && <MembershipCardPage navigate={navigate}/>}
        {page === "notFound" && <NotFoundPage navigate={navigate}/>}
      </main>
      <Footer navigate={navigate}/>
      {tweaksOpen && (
        <div className="tweaks-panel active">
          <h4>Tweaks</h4>
          <div className="row">
            <span>Gold accent</span>
            <input type="color" value={tweaks.accent} onChange={e => setTweak("accent", e.target.value)}/>
          </div>
          <div className="row">
            <span>Headline</span>
            <select value={tweaks.headlineFont} onChange={e => setTweak("headlineFont", e.target.value)}>
              <option>Cormorant Garamond</option>
              <option>EB Garamond</option>
              <option>Playfair Display</option>
            </select>
          </div>
          <div className="row" style={{marginTop: 8, paddingTop: 8, borderTop: "1px solid var(--rule-dark)"}}>
            <span style={{fontSize: 10, color: "var(--muted-light)"}}>Use top nav to preview all 7 pages</span>
          </div>
        </div>
      )}
      <style>{`
        .display, .brand-name { font-family: "${tweaks.headlineFont}", Georgia, serif !important; }
      `}</style>
    </>
  );
};

const Header = ({ page, navigate }) => {
  // Pages where the header sits on a dark hero — use translucent-dark header
  const darkHeroPages = ["home", "about", "leadership", "projects", "news", "membership", "donate", "contact"];
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const dark = darkHeroPages.includes(page) && !scrolled;

  return (
    <header className={`header ${dark ? "dark" : ""}`}>
      <div className="header-inner">
        <Brand
          dark={dark}
          href={ROUTES_BY_PAGE.home}
          onClick={e => handleInternalNavigation(e, "home", navigate)}
        />
        <nav className="nav">
          {NAV.map(n => (
            <a
              key={n.id}
              href={n.path}
              className={page === n.id ? "active" : ""}
              onClick={e => handleInternalNavigation(e, n.id, navigate)}
            >
              {n.label}
            </a>
          ))}
        </nav>
        <div className="header-cta">
          <button className={`btn btn-link ${dark ? "on-dark" : ""}`} onClick={() => navigate("donate")}>
            Donate
          </button>
          <button
            className={`btn btn-ghost ${dark ? "on-dark" : ""}`}
            onClick={() => {
              navigate("membership");
              window.setTimeout(() => {
                document.getElementById("membership-application")?.scrollIntoView({ behavior: "smooth", block: "start" });
              }, 120);
            }}
            style={{padding: "12px 20px"}}
          >
            Join
          </button>
          <button className="menu-btn" onClick={() => setMobileOpen(!mobileOpen)} style={{
            display: "none",
            background: "transparent", border: 0, cursor: "pointer", padding: 8,
            color: "inherit"
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
              <path d={mobileOpen ? "M6 6L18 18M6 18L18 6" : "M4 7h16M4 12h16M4 17h16"}/>
            </svg>
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div style={{
          borderTop: `1px solid ${dark ? "var(--rule-dark)" : "var(--rule)"}`,
          padding: "20px var(--gutter)",
          display: "flex", flexDirection: "column", gap: 4,
        }}>
          {NAV.map(n => (
            <a
              key={n.id}
              href={n.path}
              onClick={e => {
                if (isModifiedEvent(e)) return;
                e.preventDefault();
                navigate(n.id);
                setMobileOpen(false);
              }}
              style={{
              padding: "12px 0",
              fontSize: 18,
              fontFamily: "var(--serif)",
              color: page === n.id ? "var(--gold-2)" : "inherit",
              cursor: "pointer",
              borderBottom: `1px solid ${dark ? "var(--rule-dark)" : "var(--rule)"}`,
              textDecoration: "none",
            }}
            >
              {n.label}
            </a>
          ))}
        </div>
      )}
      <style>{`
        @media (max-width: 960px) {
          .menu-btn { display: inline-flex !important; }
          .nav { display: none; }
        }
      `}</style>
    </header>
  );
};

const Footer = ({ navigate }) => {
  const [email, setEmail] = React.useState("");
  const [subscribed, setSubscribed] = React.useState(false);
  const socialLinks = [
    { label: "LinkedIn", href: "https://www.linkedin.com/company/central-asian-american-bar-association/posts/?feedView=all" },
    { label: "Email", href: "mailto:info@caabar.com" },
    { label: "Instagram", href: "https://www.instagram.com/caabar_com" },
    { label: "Facebook", href: "https://www.facebook.com/caabarassociation" },
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        {/* Top grid */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1.4fr 1fr 1fr 1.4fr",
          gap: "clamp(24px, 5vw, 64px)",
          paddingBottom: 75,
          borderBottom: "1px solid var(--rule-dark)",
        }} className="footer-grid">
          {/* Brand col */}
          <div>
            <div style={{display: "flex", alignItems: "center", gap: 14, marginBottom: 24}}>
              <img src="/assets/caaba-logo.png" alt="CAABA" style={{height: "clamp(58px, 9vw, 76px)", width: "auto", display: "block"}}/>
            </div>
            <div className="eyebrow light" style={{marginBottom: 16}}>Est. 2026 · Richmond, Texas</div>
            <p style={{fontSize: 14.5, lineHeight: 1.65, color: "#A9B3BF", maxWidth: "36ch"}}>
              Central Asian American Bar Association — a professional home for lawyers connected to Central Asia in the United States.
            </p>
            <div style={{marginTop: 24, display: "flex", gap: 16}}>
              {socialLinks.map(s => (
                <a key={s.label} href={s.href} target={s.href.startsWith("http") ? "_blank" : undefined} rel={s.href.startsWith("http") ? "noopener noreferrer" : undefined} style={{
                  fontFamily: "var(--sans)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase",
                  borderBottom: "1px solid rgba(228,203,136,0.35)", paddingBottom: 2,
                }}>{s.label}</a>
              ))}
            </div>
          </div>

          {/* Nav cols */}
          <div>
            <div className="eyebrow light" style={{marginBottom: 16}}>Organization</div>
            <ul style={{listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: 10}}>
              {["about", "leadership", "projects", "news"].map(k => (
                <li key={k}>
                  <a
                    href={ROUTES_BY_PAGE[k]}
                    onClick={e => handleInternalNavigation(e, k, navigate)}
                    style={{cursor: "pointer", fontSize: 15, fontFamily: "var(--serif)"}}
                  >
                    {NAV.find(n => n.id === k).label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <div className="eyebrow light" style={{marginBottom: 16}}>Engage</div>
            <ul style={{listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: 10}}>
              {["membership", "donate", "contact"].map(k => (
                <li key={k}>
                  <a
                    href={ROUTES_BY_PAGE[k]}
                    onClick={e => handleInternalNavigation(e, k, navigate)}
                    style={{cursor: "pointer", fontSize: 15, fontFamily: "var(--serif)"}}
                  >
                    {NAV.find(n => n.id === k).label}
                  </a>
                </li>
              ))}
            </ul>
          </div>

          {/* Newsletter */}
          <div>
            <div className="eyebrow light" style={{marginBottom: 16}}>Newsletter</div>
            <p style={{fontSize: 14.5, color: "#A9B3BF", lineHeight: 1.6, marginBottom: 20}}>
              Occasional updates on CAABA programming, new initiatives, and events.
            </p>
            {subscribed ? (
              <p style={{fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 15, color: "var(--gold-soft)"}}>
                Thank you. You'll hear from us soon.
              </p>
            ) : (
              <form onSubmit={e => {e.preventDefault(); if (email) setSubscribed(true);}} style={{display: "flex", gap: 0, borderBottom: "1px solid var(--rule-dark)"}}>
                <input placeholder="your@email.com" value={email} onChange={e => setEmail(e.target.value)} style={{flex: 1, borderBottom: 0, padding: "12px 0", color: "var(--paper)"}}/>
                <button type="submit" style={{
                  background: "transparent", border: 0, color: "var(--gold-soft)",
                  cursor: "pointer", padding: "12px 0", fontFamily: "var(--mono)", fontSize: 10.5,
                  letterSpacing: "0.18em", textTransform: "uppercase",
                }}>
                  Subscribe →
                </button>
              </form>
            )}
          </div>
        </div>

        <div style={{
          padding: "28px 0",
          borderBottom: "1px solid var(--rule-dark)",
          color: "#A9B3BF",
        }}>
          <div className="eyebrow light" style={{marginBottom: 12}}>Disclaimer</div>
          <p style={{fontSize: 12.5, lineHeight: 1.7, maxWidth: "92ch", margin: 0}}>
            This website is for informational and networking purposes only. The Association does not provide legal services or legal advice. The Association does not engage in the unauthorized practice of law in any U.S. jurisdiction. No attorney-client relationship is formed through this website or through membership in the Association. Some members may be licensed attorneys in the United States, while others are licensed only in foreign jurisdictions or are not licensed to practice law. Legal services, if any, are provided solely by individual licensed attorneys and not by the Association.
          </p>
        </div>

        {/* Bottom bar */}
        <div style={{
          paddingTop: 28, display: "flex", justifyContent: "space-between",
          alignItems: "center", flexWrap: "wrap", gap: 12,
          fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.1em", color: "#7A8592",
        }}>
          <div>© 2026 Central Asian American Bar Association. All rights reserved.</div>
          <div style={{display: "flex", gap: 24}}>
            {LEGAL_NAV.map(item => (
              <a key={item.id} href={item.path} onClick={e => handleInternalNavigation(e, item.id, navigate)}>
                {item.label}
              </a>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 600px) {
          .footer-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </footer>
  );
};

const NotFoundPage = ({ navigate }) => (
  <div className="page">
    <section style={{background: "var(--ink)", color: "var(--paper)", padding: "clamp(80px, 12vw, 144px) 0"}}>
      <div className="wrap" style={{textAlign: "center"}}>
        <span className="eyebrow light">404</span>
        <h1 className="display" style={{fontSize: "clamp(42px, 7vw, 96px)", lineHeight: 1.02, marginTop: 20, marginBottom: 24}}>
          This page does not exist.
        </h1>
        <p style={{fontSize: "clamp(17px, 1.5vw, 20px)", lineHeight: 1.6, color: "#C9D2DC", maxWidth: "36ch", margin: "0 auto 36px"}}>
          The requested route was not found in this CAABA site build.
        </p>
        <button className="btn btn-primary on-dark" onClick={() => navigate("home")}>
          Return Home <Arrow/>
        </button>
      </div>
    </section>
  </div>
);

Object.assign(window, { App, Header, Footer, NotFoundPage });
