/* Main app — screen switcher (prototype navigator) + tweaks + routing */

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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "orange",
  "formLayout": "stepped",
  "invitedCompany": "Imprimerie Lemercier",
  "showProtoNav": true
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = useStateApp("welcome");      // adherent screen
  const [adminArea, setAdminArea] = useStateApp("survey");
  const [adminTab, setAdminTab] = useStateApp("campaigns");
  const [campaignId, setCampaignId] = useStateApp("ia-2026");
  const [respondentId, setRespondentId] = useStateApp(null);
  const [authed, setAuthed] = useStateApp(false);
  const [submission, setSubmission] = useStateApp(null);

  const data = window.FESPA_DATA;

  // Apply accent override
  useEffectApp(() => {
    const r = document.documentElement;
    if (tweaks.accent === "red") {
      r.style.setProperty("--brand", "#0F1822");
      r.style.setProperty("--brand-strong", "#000000");
      r.style.setProperty("--accent", "#D8232A");
      r.style.setProperty("--accent-strong", "#A8161D");
      r.style.setProperty("--accent-soft", "#FCE3E5");
      r.style.setProperty("--link-hover", "#D8232A");
    } else if (tweaks.accent === "navy") {
      r.style.setProperty("--brand", "var(--byi-navy-800)");
      r.style.setProperty("--brand-strong", "var(--byi-navy-900)");
      r.style.setProperty("--accent", "var(--byi-cyan-500)");
      r.style.setProperty("--accent-strong", "#0098D1");
      r.style.setProperty("--accent-soft", "var(--byi-cyan-100)");
      r.style.setProperty("--link-hover", "var(--byi-cyan-500)");
    } else {
      r.style.removeProperty("--brand");
      r.style.removeProperty("--brand-strong");
      r.style.removeProperty("--accent");
      r.style.removeProperty("--accent-strong");
      r.style.removeProperty("--accent-soft");
      r.style.removeProperty("--link-hover");
    }
  }, [tweaks.accent]);

  const openRespondent = (id) => {
    setRespondentId(id);
    setAdminTab("detail");
  };
  const adjacent = (delta) => {
    const idx = data.respondents.findIndex(r => r.id === respondentId);
    const next = data.respondents[(idx + delta + data.respondents.length) % data.respondents.length];
    setRespondentId(next.id);
  };

  // Render
  const isAdmin = screen.startsWith("admin");
  return (
    <>
      {tweaks.showProtoNav && (
        <ProtoNav
          screen={screen}
          setScreen={setScreen}
          adminTab={isAdmin ? adminTab : null}
          setAdminTab={setAdminTab}
          authed={authed}
        />
      )}

      <div className="screen-wrap" data-screen-label={screen}>
        {screen === "welcome" && (
          <AdherentWelcome tweaks={tweaks} onStart={() => setScreen("form")} />
        )}
        {screen === "form" && (
          <AdherentQuestionnaire
            tweaks={tweaks}
            onSubmit={(a) => { setSubmission(a); setScreen("thanks"); }}
            onBackHome={() => setScreen("welcome")}
          />
        )}
        {screen === "thanks" && (
          <AdherentThankYou answers={submission} onBackHome={() => setScreen("welcome")} />
        )}
        {screen === "admin" && !authed && (
          <AdminLogin onLogin={() => { setAuthed(true); }} />
        )}
        {screen === "admin" && authed && (
          <AdminShell
            area={adminArea}
            tab={adminTab === "detail" ? "respondents" : adminTab}
            onArea={(a) => {
              setAdminArea(a);
              const first = window.ADMIN_AREAS.find(x => x.id === a).tabs[0][0];
              setAdminTab(first);
            }}
            onTab={(t) => setAdminTab(t)}
            onLogout={() => { setAuthed(false); }}
            campaignId={campaignId}
            onCampaignChange={(id) => setCampaignId(id)}
          >
            {(() => {
              const camp = window.FESPA_CAMPAIGNS.find(c => c.id === campaignId);
              const isPrimary = camp && camp.isPrimary;
              const surveyContent = () => {
                // For non-primary campaigns, only show a closed-notice on dashboard
                if (!isPrimary && adminTab === "dashboard") {
                  return <window.CampaignClosedNotice campaign={camp}/>;
                }
                if (adminTab === "campaigns") {
                  return <window.AdminCampaigns onSelectCampaign={(id) => {
                    setCampaignId(id);
                    const camp = window.FESPA_CAMPAIGNS.find(c => c.id === id);
                    if (camp.status === "draft") {
                      setAdminTab("invitations");
                    } else {
                      setAdminTab("dashboard");
                    }
                  }}/>;
                }
                if (adminTab === "dashboard") {
                  return <AdminDashboard data={data} onOpenRespondent={openRespondent} />;
                }
                if (adminTab === "respondents") {
                  return <AdminRespondents data={data} onOpen={openRespondent} />;
                }
                if (adminTab === "detail" && respondentId) {
                  return <AdminRespondentDetail
                    data={data}
                    id={respondentId}
                    onBack={() => setAdminTab("respondents")}
                    onNext={() => adjacent(1)}
                    onPrev={() => adjacent(-1)}
                  />;
                }
                if (adminTab === "invitations") {
                  return <AdminInvitations data={data} />;
                }
                return null;
              };
              return (
                <>
                  {adminArea === "survey" && surveyContent()}
                  {adminArea === "training" && adminTab === "sessions" && (
                    <window.AdminTrainingSessions data={data} />
                  )}
                  {adminArea === "training" && adminTab === "enrollments" && (
                    <window.AdminTrainingEnrollments data={data} />
                  )}
                  {adminArea === "training" && adminTab === "catalog" && (
                    <window.AdminTrainingCatalog data={data} />
                  )}
                  {adminArea === "planning" && adminTab === "gantt" && (
                    <window.AdminPlanningGantt />
                  )}
                  {adminArea === "planning" && adminTab === "milestones" && (
                    <window.AdminPlanningMilestones />
                  )}
                </>
              );
            })()}
          </AdminShell>
        )}
      </div>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Accent visuel">
          <window.TweakRadio
            value={tweaks.accent}
            onChange={v => setTweak("accent", v)}
            options={[
              { value: "orange", label: "BYI orange" },
              { value: "navy", label: "Cyan/navy" },
              { value: "red", label: "FESPA rouge" }
            ]}
          />
        </window.TweakSection>
        <window.TweakSection title="Démo">
          <window.TweakText
            label="Entreprise invitée (lien adhérent)"
            value={tweaks.invitedCompany}
            onChange={v => setTweak("invitedCompany", v)}
          />
          <window.TweakToggle
            label="Afficher la barre de navigation prototype"
            value={tweaks.showProtoNav}
            onChange={v => setTweak("showProtoNav", v)}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

/* ---------- Prototype navigator ---------- */
function ProtoNav({ screen, setScreen, adminTab, setAdminTab, authed }) {
  const isAdmin = screen === "admin";
  return (
    <div className="proto-nav">
      <div className="proto-nav__group">
        <span className="proto-nav__label">Adhérent</span>
        <button className={`proto-nav__btn ${screen === "welcome" ? "is-on" : ""}`} onClick={() => setScreen("welcome")}>① Accueil</button>
        <button className={`proto-nav__btn ${screen === "form" ? "is-on" : ""}`} onClick={() => setScreen("form")}>② Questionnaire</button>
        <button className={`proto-nav__btn ${screen === "thanks" ? "is-on" : ""}`} onClick={() => setScreen("thanks")}>③ Confirmation</button>
      </div>
      <div className="proto-nav__divider"></div>
      <div className="proto-nav__group">
        <span className="proto-nav__label">Admin FESPA {authed && "·"}{authed && <span className="proto-nav__authed">connecté</span>}</span>
        <button className={`proto-nav__btn ${isAdmin && !authed ? "is-on" : ""}`} onClick={() => setScreen("admin")}>🔒 Login</button>
        <button className={`proto-nav__btn ${isAdmin && authed && adminTab === "dashboard" ? "is-on" : ""}`} onClick={() => { setScreen("admin"); setAdminTab("dashboard"); }} disabled={!authed && screen !== "admin"}>📊 Dashboard</button>
        <button className={`proto-nav__btn ${isAdmin && authed && adminTab === "respondents" ? "is-on" : ""}`} onClick={() => { setScreen("admin"); setAdminTab("respondents"); }}>📋 Répondants</button>
        <button className={`proto-nav__btn ${isAdmin && authed && adminTab === "detail" ? "is-on" : ""}`} onClick={() => { setScreen("admin"); setAdminTab("detail"); }}>🔎 Détail</button>
        <button className={`proto-nav__btn ${isAdmin && authed && adminTab === "invitations" ? "is-on" : ""}`} onClick={() => { setScreen("admin"); setAdminTab("invitations"); }}>✉ Invitations</button>
      </div>
    </div>
  );
}

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