// src/app.jsx — Main App: routing + theme + tweaks

const ROUTES = ["home", "about", "services", "contacts", "request", "privacy", "consent"];

// Accent palettes
const ACCENTS = {
  orange:   { c: "#FF5B2E", l: "#FF7B5C", soft: "rgba(255, 91, 46, 0.12)",  line: "rgba(255, 91, 46, 0.30)",  fg: "#ffffff", dark_c: "#FF5B2E", light_c: "#E94818" },
  copper:   { c: "#D97757", l: "#E89478", soft: "rgba(217, 119, 87, 0.12)", line: "rgba(217, 119, 87, 0.30)", fg: "#ffffff", dark_c: "#E08A6A", light_c: "#B85935" },
  lime:     { c: "#D4FF3E", l: "#E5FF6B", soft: "rgba(212, 255, 62, 0.10)", line: "rgba(212, 255, 62, 0.36)", fg: "#0a0a0c", dark_c: "#D4FF3E", light_c: "#6FAD00" },
  violet:   { c: "#7C5CFF", l: "#9F86FF", soft: "rgba(124, 92, 255, 0.12)", line: "rgba(124, 92, 255, 0.28)", fg: "#ffffff", dark_c: "#7C5CFF", light_c: "#5B3FD9" },
  azure:    { c: "#38BDF8", l: "#5DCBFA", soft: "rgba(56, 189, 248, 0.10)", line: "rgba(56, 189, 248, 0.30)", fg: "#0a0a0c", dark_c: "#38BDF8", light_c: "#0284C7" },
};

// Font stacks
const FONTS = {
  manrope:      { ui: '"Manrope", ui-sans-serif, system-ui, sans-serif',       label: "Manrope",       hint: "Нейтральный гротеск" },
  intertight:   { ui: '"Inter Tight", ui-sans-serif, system-ui, sans-serif',   label: "Inter Tight",   hint: "Компактный, инженерный" },
  spacegrotesk: { ui: '"Space Grotesk", ui-sans-serif, system-ui, sans-serif', label: "Space Grotesk", hint: "Геометричный, дерзкий" },
  onest:        { ui: '"Onest", ui-sans-serif, system-ui, sans-serif',         label: "Onest",         hint: "Тёплый минимал" },
  marcellus:    { ui: '"Marcellus", "Cormorant Garamond", Georgia, serif',     label: "Marcellus",     hint: "В тон логотипу — классический wide" },
};

function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [route, setRoute] = useState(() => {
    const h = window.location.hash.replace(/^#/, "");
    return ROUTES.includes(h) ? h : "home";
  });

  // Apply theme + accent + font as CSS variables
  useEffect(() => {
    const html = document.documentElement;
    html.setAttribute("data-theme", t.theme || "dark");

    const accent = ACCENTS[t.accent] || ACCENTS.orange;
    // theme-aware accent (slightly darker on light bg for contrast)
    const isDark = (t.theme || "dark") === "dark";
    const main = isDark ? accent.dark_c : accent.light_c;
    const hover = accent.l;
    html.style.setProperty("--accent", main);
    html.style.setProperty("--accent-2", hover);
    html.style.setProperty("--accent-soft", accent.soft);
    html.style.setProperty("--accent-line", accent.line);
    html.style.setProperty("--accent-fg", accent.fg);

    const font = FONTS[t.font] || FONTS.manrope;
    html.style.setProperty("--font-ui", font.ui);
  }, [t.theme, t.accent, t.font]);

  // Hash sync
  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, "");
      if (ROUTES.includes(h)) setRoute(h);
      else if (h === "") setRoute("home");
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffect(() => {
    if (typeof updateSeo === "function") updateSeo(route);
  }, [route]);

  function navigate(to) {
    if (!ROUTES.includes(to)) return;
    setRoute(to);
    window.location.hash = to === "home" ? "" : to;
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  let Page;
  switch (route) {
    case "about": Page = AboutPage; break;
    case "services": Page = ServicesPage; break;
    case "contacts": Page = ContactsPage; break;
    case "request": Page = RequestPage; break;
    case "privacy": Page = PrivacyPage; break;
    case "consent": Page = ConsentPage; break;
    default: Page = HomePage;
  }

  // Color swatch palettes for TweakColor (curated trios)
  const accentPalettes = Object.keys(ACCENTS).map((k) => [ACCENTS[k].c, ACCENTS[k].l, ACCENTS[k].fg]);
  // Build options that pass current value through unchanged
  const currentAccentPalette = accentPalettes.find((p) => p[0] === ACCENTS[t.accent]?.c) || accentPalettes[0];

  return (
    <>
      <Header route={route} navigate={navigate} />
      <main>
        <Page navigate={navigate} key={route} />
      </main>
      <Footer navigate={navigate} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Тема" />
        <TweakRadio
          label="Режим"
          value={t.theme}
          options={["dark", "light"]}
          onChange={(v) => setTweak("theme", v)}
        />

        <TweakSection label="Акцентный цвет" />
        <AccentPicker value={t.accent} onChange={(v) => setTweak("accent", v)} />

        <TweakSection label="Шрифт" />
        <TweakSelect
          label="Семейство"
          value={t.font}
          options={Object.keys(FONTS).map((k) => ({ value: k, label: FONTS[k].label }))}
          onChange={(v) => setTweak("font", v)}
        />
        <FontPreview font={t.font} />

        <div style={{ fontSize: 11, color: "rgba(0,0,0,0.5)", lineHeight: 1.4, paddingTop: 10, borderTop: "1px solid rgba(0,0,0,0.06)" }}>
          Тёмная тема — основной режим. Акцент и шрифт можно подобрать под фирменный стиль на этапе утверждения дизайна.
        </div>
      </TweaksPanel>
    </>
  );
}

// Custom accent picker — shows swatches of the actual brand colors
function AccentPicker({ value, onChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 6, marginTop: 2 }}>
      {Object.entries(ACCENTS).map(([key, a]) => {
        const active = value === key;
        return (
          <button
            key={key}
            type="button"
            onClick={() => onChange(key)}
            title={key}
            style={{
              height: 36,
              borderRadius: 6,
              background: a.c,
              border: active ? "2px solid #29261b" : "0.5px solid rgba(0,0,0,0.15)",
              outline: active ? "2px solid rgba(255,255,255,0.7)" : "none",
              outlineOffset: -3,
              cursor: "pointer",
              position: "relative",
              padding: 0,
              transition: "transform 0.12s ease",
            }}
            onMouseEnter={(e) => (e.currentTarget.style.transform = "scale(1.05)")}
            onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
          />
        );
      })}
    </div>
  );
}

function FontPreview({ font }) {
  const f = FONTS[font] || FONTS.manrope;
  return (
    <div style={{
      padding: "10px 12px",
      background: "rgba(255,255,255,0.5)",
      border: "0.5px solid rgba(0,0,0,0.08)",
      borderRadius: 6,
      fontFamily: f.ui,
      lineHeight: 1.2,
      marginTop: 2,
    }}>
      <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: "-0.02em" }}>Импорт под ключ</div>
      <div style={{ fontSize: 11, color: "rgba(41,38,27,0.6)", marginTop: 4, fontWeight: 400, letterSpacing: 0 }}>
        Aa Bb Cc · 0123 · {f.label}
      </div>
      <div style={{ fontSize: 10, color: "rgba(41,38,27,0.5)", marginTop: 2, fontWeight: 400, letterSpacing: 0 }}>
        {f.hint}
      </div>
    </div>
  );
}

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