// src/App.jsx — top-level Alcy Mémoires chatbot

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "memoires",
  "kidMode": false,
  "textSize": 15,
  "showSidebar": true
}/*EDITMODE-END*/;

function nowTime() {
  const d = new Date();
  return d.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = React.useState("welcome"); // welcome | chat
  const [messages, setMessages] = React.useState([]);
  const [activeParcours, setActiveParcours] = React.useState("all");

  const D = window.ALCY_DATA;

  // Apply text-size CSS var
  React.useEffect(() => {
    document.documentElement.style.setProperty("--text-base", `${t.textSize}px`);
  }, [t.textSize]);

  const askQuestion = React.useCallback(async (qText) => {
    // Move to chat screen if needed and add the welcome alcy message
    setScreen("chat");

    setMessages((prev) => {
      const base = prev.length === 0
        ? [{ role: "alcy", text: D.FLOWS.welcome.text, time: nowTime() }]
        : prev;
      return [
        ...base,
        { role: "user", text: qText, time: nowTime() },
        { role: "alcy", typing: true },
      ];
    });

    // Simulate latency, then resolve
   try {
  const res = await fetch("https://n8n.bradbot.fr/webhook/88451171-6451-4cc9-93a3-3aad1692b585", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      message: qText
    })
  });

  const data = await res.json();

setMessages((prev) => {
  const out = prev.slice(0, -1); // drop typing

  out.push({
    role: "alcy",
    text: data.output || "Je n’ai pas reçu de réponse d’Alcy.",
    followups: [
      "Résoudre une photo mystère",
      "Explorer un lieu du village",
      "Découvrir un ancien métier",
      "Écouter une histoire courte",
      "Poser une question aux archives"
    ],
    time: nowTime(),
  });

  return out;
});
} catch (error) {
  setMessages((prev) => {
    const out = prev.slice(0, -1); // drop typing
    out.push({
      role: "alcy",
      text: "Je n’arrive pas à joindre les archives pour le moment.",
      time: nowTime(),
    });
    return out;
  });
}
     
  }, [D]);

  const handleFollowup = (q) => askQuestion(q);

  const handleParcours = (id) => {
    setActiveParcours(id);
    if (id === "forges")    askQuestion("Quelles étaient les 5 forges du village ?");
    if (id === "cyclisme")  askQuestion("Quand Paris–Roubaix est-elle passée à Auchy ?");
    if (id === "ecole")     askQuestion("Photos d'école d'avant 1960");
  };

  const goHome = () => {
    setScreen("welcome");
    setMessages([]);
    setActiveParcours("all");
  };

  return (
    <div
      className="app-frame"
      data-direction={t.direction}
      data-kid={t.kidMode ? "true" : "false"}
    >
      {/* Top bar */}
      <div className="topbar">
        <div className="topbar-left">
          <button onClick={goHome} className="topbar-logo" title="Accueil"
            style={{ border: 0, cursor: "pointer" }}>
            A
          </button>
          <div>
            <div className="topbar-title">Alcy Mémoires</div>
            <div className="topbar-sub">Histoire d'Auchy-lez-Orchies</div>
          </div>
        </div>

        <div className="topbar-right">
          <button
            className={`kid-toggle ${t.kidMode ? "on" : ""}`}
            onClick={() => setTweak("kidMode", !t.kidMode)}
            title="Mode jeune public"
          >
            <span className="pill">{t.kidMode ? "✿" : "✎"}</span>
            {t.kidMode ? "Mode jeune public" : "Mode adulte"}
          </button>
          <button className="icon-btn" title="Aide">?</button>
        </div>
      </div>

      {/* Main shell */}
      <div className="shell">
        {/* Sidebar */}
        <aside className="sidebar">
          <div>
            <div className="side-section-title">Parcours thématiques</div>
            <div className="parcours-list" style={{ marginTop: 8 }}>
              {D.PARCOURS.map((p) => (
                <button
                  key={p.id}
                  className={`parcours ${activeParcours === p.id ? "active" : ""}`}
                  onClick={() => handleParcours(p.id)}
                >
                  <span className="parcours-emoji">{p.icon}</span>
                  <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {p.label}
                  </span>
                  <span className="parcours-count">{p.count}</span>
                </button>
              ))}
            </div>
          </div>

          {messages.length > 0 && (
            <div>
              <div className="side-section-title">Conversation en cours</div>
              <div className="history-list" style={{ marginTop: 8 }}>
                {messages
                  .filter((m) => m.role === "user")
                  .slice(-5)
                  .reverse()
                  .map((m, i) => (
                    <div key={i} className="history-item" title={m.text}>
                      ▸ {m.text}
                    </div>
                  ))}
              </div>
            </div>
          )}

          <div style={{ marginTop: "auto", paddingTop: 14, fontSize: 11, color: "var(--text-soft)", lineHeight: 1.5 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <img src="assets/logo.png" alt="Alcy Mémoires"
                style={{ height: 22, opacity: .85 }} />
            </div>
            Exposition annuelle<br/>
            <strong style={{ color: "var(--primary)" }}>14–16 novembre 2026</strong><br/>
            Salle des fêtes, Auchy-lez-Orchies
          </div>
        </aside>

        {/* Main */}
        <main className="main">
          {screen === "welcome" ? (
            <Welcome onAsk={askQuestion} kid={t.kidMode} />
          ) : (
            <Chat
              messages={messages}
              onAsk={askQuestion}
              onFollowup={handleFollowup}
              kid={t.kidMode}
            />
          )}
        </main>
      </div>

      {/* Tweaks panel */}
      <TweaksPanel>
        <TweakSection label="Direction visuelle" />
        <TweakRadio
          label="Style"
          value={t.direction}
          options={["memoires", "atelier"]}
          onChange={(v) => setTweak("direction", v)}
        />

        <TweakSection label="Public & lisibilité" />
        <TweakToggle
          label="Mode jeune public"
          value={t.kidMode}
          onChange={(v) => setTweak("kidMode", v)}
        />
        <TweakSlider
          label="Taille du texte"
          value={t.textSize}
          min={13} max={20} step={1} unit="px"
          onChange={(v) => setTweak("textSize", v)}
        />

        <TweakSection label="Démo" />
        <TweakButton label="Retour à l'accueil" onClick={goHome} />
        <TweakButton
          label="Lancer démo : forges"
          onClick={() => askQuestion("Quelles étaient les 5 forges du village ?")}
        />
        <TweakButton
          label="Lancer démo : photos"
          onClick={() => askQuestion("Montre-moi des photos de la forge Lemaire")}
        />
        <TweakButton
          label="Lancer démo : Paris–Roubaix"
          onClick={() => askQuestion("Quand Paris–Roubaix est-elle passée à Auchy ?")}
        />
      </TweaksPanel>
    </div>
  );
}

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