// Main App — router, state, API fetch, theme, tweaks.

const DEFAULT_TWEAKS = /*EDITMODE-BEGIN*/{
  "theme": "trust",
  "fontDisplay": "Fraunces",
  "lang": "fr",
  "density": "comfortable"
}/*EDITMODE-END*/;

// Try to get API config from window (set in HTML), else empty
const API_URL = window.__API_URL__ || "";
const API_KEY = window.__API_KEY__ || "";

const THEMES = {
  trust: {
    name: "Trust Blue",
    bg: "#ffffff",
    subtle: "oklch(0.985 0.005 240)",
    border: "oklch(0.92 0.008 240)",
    chip: "oklch(0.95 0.01 240)",
    ink: "oklch(0.22 0.03 245)",
    inkMuted: "oklch(0.5 0.02 245)",
    primary: "oklch(0.52 0.17 250)",
    primaryBg: "oklch(0.96 0.025 250)",
  },
  forest: {
    name: "Forest",
    bg: "#ffffff",
    subtle: "oklch(0.985 0.006 150)",
    border: "oklch(0.92 0.01 150)",
    chip: "oklch(0.95 0.012 150)",
    ink: "oklch(0.22 0.025 160)",
    inkMuted: "oklch(0.5 0.02 160)",
    primary: "oklch(0.48 0.13 160)",
    primaryBg: "oklch(0.96 0.03 150)",
  },
  sunset: {
    name: "Sunset",
    bg: "#ffffff",
    subtle: "oklch(0.985 0.008 50)",
    border: "oklch(0.92 0.012 50)",
    chip: "oklch(0.95 0.015 50)",
    ink: "oklch(0.22 0.025 30)",
    inkMuted: "oklch(0.5 0.02 30)",
    primary: "oklch(0.58 0.17 40)",
    primaryBg: "oklch(0.96 0.035 50)",
  },
};

const FONTS = {
  Fraunces: "'Fraunces', 'Georgia', serif",
  Inter: "'Inter Tight', 'Inter', sans-serif",
  Instrument: "'Instrument Serif', serif",
};

function useTheme(key, font) {
  return React.useMemo(() => ({
    ...THEMES[key] || THEMES.trust,
    fontDisplay: FONTS[font] || FONTS.Fraunces,
  }), [key, font]);
}

// Default dates: today+7 → today+12
function defaultDate(days) {
  const d = new Date();
  d.setDate(d.getDate() + days);
  return d.toISOString().slice(0, 10);
}

function App() {
  const [tweaks, setTweaks] = React.useState(DEFAULT_TWEAKS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const theme = useTheme(tweaks.theme, tweaks.fontDisplay);
  const [lang, setLang] = React.useState(tweaks.lang || "fr");

  // routing
  const [screen, setScreen] = React.useState(() => localStorage.getItem("ap_screen") || "home");
  const [selectedId, setSelectedId] = React.useState(() => localStorage.getItem("ap_pid") || null);

  const go = React.useCallback((s, id) => {
    setScreen(s);
    if (id !== undefined) setSelectedId(id);
    localStorage.setItem("ap_screen", s);
    if (id !== undefined) localStorage.setItem("ap_pid", id);
    window.scrollTo(0, 0);
  }, []);

  // Expose so Footer links (which don't receive `go` as prop) can navigate
  React.useEffect(() => { window.__goto = go; }, [go]);

  // search state
  const [search, setSearch] = React.useState(() => ({
    airport: "CDG",
    from: defaultDate(7),
    fromTime: "08:00",
    to: defaultDate(12),
    toTime: "20:00",
  }));

  // form state
  const [form, setForm] = React.useState({
    firstName: "", lastName: "", email: "", phone: "",
    plate: "", model: "", flight: "",
    card: "", expiry: "", cvc: "",
  });
  const [extras, setExtras] = React.useState({});
  const [ref_, setRef] = React.useState("");

  // API data
  const [apiParkings, setApiParkings] = React.useState(PARKINGS);
  const [loading, setLoading] = React.useState(false);
  const [apiError, setApiError] = React.useState(null);

  React.useEffect(() => {
    if (!API_URL || !API_KEY) { setApiError("no-config"); return; }
    setLoading(true);
    fetch(`${API_URL}parkings?select=*`, {
      headers: { apikey: API_KEY, Authorization: `Bearer ${API_KEY}` },
    })
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(data => {
        if (Array.isArray(data) && data.length) {
          // Merge API fields with mock defaults for missing visual fields
          const merged = data.map((row, i) => ({ ...PARKINGS[i % PARKINGS.length], ...row }));
          setApiParkings(merged);
          setApiError(null);
        } else {
          setApiError("empty");
        }
      })
      .catch(e => setApiError(String(e)))
      .finally(() => setLoading(false));
  }, []);

  const days = React.useMemo(() => {
    const a = new Date(search.from), b = new Date(search.to);
    return Math.max(1, Math.round((b - a) / (1000 * 60 * 60 * 24)));
  }, [search.from, search.to]);

  const parking = React.useMemo(() =>
    apiParkings.find(p => p.id === selectedId) || apiParkings[0],
    [apiParkings, selectedId]
  );

  const onConfirm = () => {
    const r = "APK-" + Math.random().toString(36).slice(2, 6).toUpperCase() + "-" + Math.random().toString(36).slice(2, 6).toUpperCase();
    setRef(r);
    go("confirm");
  };

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

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

  return (
    <div data-screen-label={`00 ${screen}`} style={{
      fontFamily: FONTS.Inter,
      color: theme.ink,
      background: theme.bg,
      minHeight: "100vh",
      fontSize: 14,
    }}>
      <style>{`
        @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
        body { margin: 0; font-family: ${FONTS.Inter}; -webkit-font-smoothing: antialiased; }
        * { box-sizing: border-box; }
        ::selection { background: ${theme.primaryBg}; }
        input[type=date]::-webkit-calendar-picker-indicator, input[type=time]::-webkit-calendar-picker-indicator {
          opacity: 0.5; cursor: pointer;
        }
      `}</style>

      <Header lang={lang} setLang={setLang} go={go} theme={theme}/>

      {screen === "home" && <Landing lang={lang} search={search} setSearch={setSearch} go={go} theme={theme}/>}
      {screen === "parkings" && <ParkingsIndex lang={lang} theme={theme} go={go} setSearch={setSearch} parkings={apiParkings}/>}
      {screen === "results" && <Results lang={lang} search={search} setSearch={setSearch} go={go} theme={theme} results={apiParkings} loading={loading} apiError={apiError}/>}
      {screen === "detail" && <Detail lang={lang} search={search} go={go} theme={theme} parking={parking} days={days}/>}
      {screen === "booking" && <Booking lang={lang} search={search} go={go} theme={theme} parking={parking} days={days} form={form} setForm={setForm} extras={extras} setExtras={setExtras} onConfirm={onConfirm}/>}
      {screen === "confirm" && <Confirmation lang={lang} search={search} theme={theme} parking={parking} days={days} form={form} ref_={ref_} go={go}/>}
      {screen === "services" && <ServicesPage lang={lang} theme={theme} go={go}/>}
      {screen === "legal" && <LegalPage lang={lang} theme={theme}/>}
      {screen === "terms" && <TermsPage lang={lang} theme={theme}/>}
      {screen === "contact" && <ContactPage lang={lang} theme={theme}/>}

      {tweaksOpen && <TweaksPanel tweaks={tweaks} update={updateTweak} theme={theme} onClose={() => setTweaksOpen(false)}/>}
    </div>
  );
}

function TweaksPanel({ tweaks, update, theme, onClose }) {
  return (
    <div style={{
      position: "fixed", right: 20, bottom: 20, width: 260, zIndex: 100,
      background: theme.bg, border: "1px solid " + theme.border, borderRadius: 14,
      boxShadow: "0 20px 60px rgba(0,0,0,0.18)", padding: 16,
      fontFamily: FONTS.Inter, fontSize: 13, color: theme.ink,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <span style={{ fontFamily: theme.fontDisplay, fontSize: 16, fontWeight: 700 }}>Tweaks</span>
        <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", color: theme.inkMuted, padding: 4 }}>
          <Icon name="x" size={16}/>
        </button>
      </div>

      <TweakRow label="Theme">
        <div style={{ display: "flex", gap: 6 }}>
          {Object.entries(THEMES).map(([k, v]) => (
            <button key={k} onClick={() => update("theme", k)} title={v.name} style={{
              width: 28, height: 28, borderRadius: 8, background: v.primary,
              border: "2px solid " + (tweaks.theme === k ? theme.ink : "transparent"),
              cursor: "pointer",
            }}/>
          ))}
        </div>
      </TweakRow>

      <TweakRow label="Display font">
        <select value={tweaks.fontDisplay} onChange={(e) => update("fontDisplay", e.target.value)} style={selectStyle(theme)}>
          {Object.keys(FONTS).map(f => <option key={f} value={f}>{f}</option>)}
        </select>
      </TweakRow>

      <TweakRow label="Language">
        <div style={{ display: "flex", borderRadius: 8, background: theme.subtle, padding: 2 }}>
          {["fr", "en"].map(l => (
            <button key={l} onClick={() => update("lang", l)} style={{
              flex: 1, padding: "5px 10px", border: "none", borderRadius: 6, cursor: "pointer",
              background: tweaks.lang === l ? theme.bg : "transparent",
              fontWeight: 600, fontSize: 12, color: tweaks.lang === l ? theme.ink : theme.inkMuted,
              boxShadow: tweaks.lang === l ? "0 1px 2px rgba(0,0,0,0.06)" : "none",
            }}>{l.toUpperCase()}</button>
          ))}
        </div>
      </TweakRow>
    </div>
  );
}

function TweakRow({ label, children }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12, gap: 10 }}>
      <span style={{ fontSize: 12, fontWeight: 500, opacity: 0.75 }}>{label}</span>
      {children}
    </div>
  );
}

function selectStyle(theme) {
  return {
    border: "1px solid " + theme.border, borderRadius: 8,
    padding: "5px 8px", fontSize: 12, fontFamily: "inherit",
    background: theme.bg, color: theme.ink,
  };
}

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