// Ofok — app shell

function OfokApp() {
  const [lang, setLang] = React.useState("en");
  const [purpose, setPurpose] = React.useState(null);
  const [type, setType] = React.useState(null);
  const [active, setActive] = React.useState(null);
  const [projects, setProjects] = React.useState(OFOK_PROJECTS_FALLBACK);
  const [projectsLoading, setProjectsLoading] = React.useState(true);
  const t = OFOK_I18N[lang];

  React.useEffect(() => {
    fetch("/api/projects")
      .then((r) => r.json())
      .then((data) => {
        setProjects(data);
        setProjectsLoading(false);
        const param = new URLSearchParams(location.search).get("project");
        if (param) {
          const found = data.find((p) => p.id === param);
          if (found) setActive(found);
        }
      })
      .catch(() => setProjectsLoading(false));
  }, []);

  React.useEffect(() => {
    const root = document.documentElement;
    root.lang = lang;
    root.dir = t.dir;
  }, [lang]);

  const scrollToId = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 76;
    window.scrollTo({ top: y, behavior: "smooth" });
  };
  const onNav = (target) => {
    if (target === "top") window.scrollTo({ top: 0, behavior: "smooth" });
    else if (target === "flow") scrollToId("ofk-flow");
    else if (target === "about") scrollToId("ofk-about");
    else if (target === "submit") scrollToId("ofk-submit");
  };

  const handleSetPurpose = (v) => {
    setPurpose(v);
    if (v) setTimeout(() => scrollToId("ofk-flow"), 50);
  };
  const handleSetType = (v) => {
    setType(v);
    if (v) setTimeout(() => scrollToId("ofk-grid"), 250);
  };

  return (
    <div className="ofk-page">
      <OfokNavbar
        t={t}
        lang={lang}
        onToggleLang={() => setLang(lang === "en" ? "ar" : "en")}
        onNav={onNav}
      />
      <OfokHero t={t} lang={lang} autoplay={true} onCta={() => scrollToId("ofk-flow")} />
      <OfokFlow
        t={t}
        purpose={purpose}
        type={type}
        setPurpose={handleSetPurpose}
        setType={handleSetType}
      />
      <OfokGrid
        t={t}
        lang={lang}
        purpose={purpose}
        type={type}
        setPurpose={handleSetPurpose}
        setType={handleSetType}
        onReset={() => {
          setPurpose(null);
          setType(null);
        }}
        onOpen={(p) => setActive(p)}
        projects={projects}
        projectsLoading={projectsLoading}
      />
      <OfokAbout t={t} />
      <OfokSubmit t={t} />
      <OfokFooter t={t} />

      <OfokDetail t={t} lang={lang} project={active} onClose={() => setActive(null)} />
      <OfokWhatsApp t={t} />
    </div>
  );
}

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