// =====================================================
// APP — router + tweaks panel
// =====================================================

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E85A1F",
  "ocean": "#5BB4D4",
  "showRoute": true,
  "darkFooter": true
}/*EDITMODE-END*/;

function parseHash() {
  const hash = window.location.hash || "#/";
  // #/escale/:id
  const m = hash.match(/^#\/escale\/(.+)$/);
  if (m) return { route: "fiche", param: m[1] };
  if (hash.startsWith("#/explorer")) {
    const m = hash.match(/[?&]itin=([^&]+)/);
    return { route: "explorer", param: m ? m[1] : null };
  }
  if (hash.startsWith("#/escales")) return { route: "escales", param: null };
  if (hash.startsWith("#/calendrier")) return { route: "calendrier", param: null };
  if (hash.startsWith("#/inspirations")) return { route: "inspirations", param: null };
  if (hash.startsWith("#/operateurs")) return { route: "operateurs", param: null };
  if (hash.startsWith("#/contact")) return { route: "contact", param: null };
  return { route: "accueil", param: null };
}

const App = () => {
  const [hash, setHash] = React.useState(window.location.hash || "#/");
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [syncBanner, setSyncBanner] = React.useState(null); // null | "loading" | "ok" | "cached" | "error"
  const [syncMsg, setSyncMsg]       = React.useState("");

  // Synchronisation Google Sheets au démarrage
  React.useEffect(() => {
    if (!window.SheetSync) return;
    setSyncBanner("loading");
    window.SheetSync.load().then(res => {
      if (res.ok) {
        if (res.cached) {
          setSyncBanner(null); // silencieux si données fraîches du cache
        } else {
          setSyncBanner("ok");
          const now = new Date();
          const dt = now.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' })
                   + ' à ' + now.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
          setSyncMsg(`Données mises à jour le ${dt}`);
          setTimeout(() => setSyncBanner(null), 5000);
        }
      } else {
        setSyncBanner("error");
        setSyncMsg("Mise à jour impossible — données locales utilisées");
        setTimeout(() => setSyncBanner(null), 8000);
      }
    });
  }, []);

  // Hash routing
  React.useEffect(() => {
    const onHash = () => {
      setHash(window.location.hash || "#/");
      window.scrollTo(0, 0);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const navigate = React.useCallback((to) => {
    if (window.location.hash === to) {
      window.scrollTo({ top: 0, behavior: "instant" });
      return;
    }
    window.location.hash = to;
  }, []);

  // Apply tweaks as CSS vars
  React.useEffect(() => {
    document.documentElement.style.setProperty("--c-terra", tweaks.accent);
    document.documentElement.style.setProperty("--c-ocean", tweaks.ocean);
  }, [tweaks]);

  // Tweaks message protocol
  React.useEffect(() => {
    const onMsg = (ev) => {
      const d = ev.data || {};
      if (d.type === "__activate_edit_mode") setTweaksOpen(true);
      if (d.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

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

  const { route, param } = parseHash();

  // Map route to header active state
  const headerRoute = route === "fiche" ? "escales" : route;

  return (
    <div className="app">
      <Header route={headerRoute} navigate={navigate}/>

      {/* Bandeau de synchronisation */}
      {syncBanner === "loading" && (
        <div className="sync-banner sync-loading">
          <span className="sync-spinner"/>Mise à jour des données…
        </div>
      )}
      {syncBanner === "ok" && (
        <div className="sync-banner sync-ok">
          <Icon name="check" size={13} stroke={2.5}/>{syncMsg}
          <button className="sync-close" onClick={() => setSyncBanner(null)}>×</button>
        </div>
      )}
      {syncBanner === "error" && (
        <div className="sync-banner sync-error">
          <Icon name="alert" size={13} stroke={2}/>{syncMsg}
          <button className="sync-close" onClick={() => setSyncBanner(null)}>×</button>
        </div>
      )}

      {route === "accueil"      && <HomePage navigate={navigate}/>}
      {route === "explorer"     && <ExplorerPage navigate={navigate} itinIds={param ? param.split(',') : null}/>}
      {route === "escales"      && <EscalesPage navigate={navigate}/>}
      {route === "fiche"        && <FichePage escaleId={param} navigate={navigate}/>}
      {route === "calendrier"   && <CalendrierPage navigate={navigate}/>}
      {route === "inspirations" && <InspirationsPage navigate={navigate}/>}
      {route === "operateurs"   && <OperateursPage navigate={navigate}/>}
      {route === "contact"      && <ContactPage navigate={navigate}/>}

      <Footer navigate={navigate}/>

      {tweaksOpen && (
        <TweaksPanel
          tweaks={tweaks}
          setTweak={setTweak}
          onClose={() => { setTweaksOpen(false); window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); }}
        />
      )}
    </div>
  );
};

// ===========================================
// Tweaks panel
// ===========================================
const TweaksPanel = ({ tweaks, setTweak, onClose }) => {
  const accents = [
    { name: "Terre cuite", v: "#E85A1F" },
    { name: "Or institutionnel", v: "#C68A1F" },
    { name: "Bourbon vanille", v: "#9C6A2A" },
    { name: "Corail", v: "#D14B6A" }
  ];
  const oceans = [
    { name: "Turquoise", v: "#5BB4D4" },
    { name: "Lagon", v: "#3D9BBF" },
    { name: "Profond", v: "#2C7CA0" },
    { name: "Pâle", v: "#A8D5E7" }
  ];
  return (
    <div className="tweaks-host" style={{
      width: 320, background: "#fff", border: "1px solid var(--c-line)",
      borderRadius: 14, boxShadow: "var(--shadow-lg)", padding: 20,
      fontFamily: "var(--f-ui)"
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <div>
          <div className="h-eyebrow" style={{ color: "var(--c-terra)" }}>Tweaks</div>
          <div className="h-card" style={{ fontSize: 20, marginTop: 2 }}>Personnaliser</div>
        </div>
        <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 50, background: "var(--c-bone)", border: "1px solid var(--c-line)", display: "grid", placeItems: "center", cursor: "pointer" }}>
          <Icon name="x" size={14}/>
        </button>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <SwatchRow label="Couleur d'accent" value={tweaks.accent} options={accents} onChange={v => setTweak("accent", v)}/>
        <SwatchRow label="Bleu océan"        value={tweaks.ocean}  options={oceans}  onChange={v => setTweak("ocean", v)}/>
      </div>

      <p className="note" style={{ marginTop: 14, fontSize: 11 }}>
        Les ajustements affectent la palette globale du site. Les autres tokens
        restent ancrés sur la charte du Ministère.
      </p>
    </div>
  );
};

const SwatchRow = ({ label, value, options, onChange }) => (
  <div>
    <div className="h-eyebrow" style={{ marginBottom: 8, color: "var(--c-navy)" }}>{label}</div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
      {options.map(o => (
        <button key={o.v} onClick={() => onChange(o.v)} title={o.name} style={{
          height: 36, borderRadius: 6,
          background: o.v, cursor: "pointer",
          border: value === o.v ? "2px solid var(--c-navy)" : "1px solid var(--c-line)",
          boxShadow: value === o.v ? "0 0 0 3px rgba(26,42,79,.15)" : "none"
        }}/>
      ))}
    </div>
  </div>
);

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