// app.jsx — root: state, routing, tweaks
const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accents": ["#ff3df0", "#8b5cff", "#2de2ff"],
  "glass": 22,
  "glow": 100,
  "typeface": "Moderna",
  "radius": "Cápsula"
}/*EDITMODE-END*/;

const TYPEFACES = {
  "Moderna":  '"Space Grotesk", "Inter", sans-serif',
  "Editorial":'"Fraunces", Georgia, serif',
  "Técnica":  '"Space Mono", monospace',
};
const RADII = { "Mancha": 14, "Burbuja": 22, "Cápsula": 30 };

const seedPosts = [
  { id: "p1", user: "@dani.cl", modelId: "iphone-15-pro", design: { design: "conic-gradient(from 200deg,#ff3df0,#ffb24d,#3dffa8,#2de2ff,#8b5cff,#ff3df0)" }, caption: "Quedó increíble el prisma 🌈", likes: 248, backdrop: "linear-gradient(160deg,#2a1c5e,#0d0a22)" },
  { id: "p2", user: "@valen", modelId: "samsung-s25-ultra", design: { base: "#0d0a22", pattern: "dots", texts: [{ value: "stargirl", x: 50, y: 80, size: 24, color: "#ff3df0", font: '"Space Grotesk",sans-serif', weight: 700, glow: true }] }, caption: "mi vibe en una carcasa ✨", likes: 412, backdrop: "linear-gradient(160deg,#3a1d6e,#0d0a22)", fromPurchase: true },
  { id: "p3", user: "@matix", modelId: "xiaomi-redmi-note-13-5g", design: { design: "linear-gradient(135deg,#2de2ff,#3dffa8 60%,#8b5cff)" }, caption: "Jade Pulse es arte", likes: 187, backdrop: "linear-gradient(160deg,#143a4a,#0d0a22)" },
  { id: "p4", user: "@flo.rs", modelId: "iphone-14", design: { base: "#ff3df0", pattern: "stars" }, caption: "rosada y con estrellitas 💖", likes: 356, backdrop: "linear-gradient(160deg,#4a1d52,#0d0a22)", fromPurchase: true },
  { id: "p5", user: "@theo", modelId: "iphone-15-pro", design: { design: "linear-gradient(160deg,#ff3df0,#ff7a3d 50%,#ffd84d)" }, caption: "Neon Sunset 🔥", likes: 521, backdrop: "linear-gradient(160deg,#5e2a1c,#0d0a22)" },
  { id: "p6", user: "@cami", modelId: "samsung-s24", design: { base: "#8b5cff", pattern: "grid", texts: [{ value: "CAMI", x: 50, y: 50, size: 34, color: "#ffffff", font: '"Space Grotesk",sans-serif', weight: 700, glow: false }] }, caption: "con mis iniciales", likes: 143, backdrop: "linear-gradient(160deg,#2e1c6e,#0d0a22)" },
];

function load(key, def) { try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : def; } catch (e) { return def; } }

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [section, setSection] = useState("home");
  const [model, setModel] = useState(null);
  const [design, setDesign] = useState({ base: "#1b1740", pattern: "none", design: null, texts: [], images: [], accessories: [] });
  const [cart, setCart] = useState([]);
  const [count, setCount] = useState(() => load("cc_count", 3000));
  const [posts, setPosts] = useState(() => load("cc_posts", seedPosts));
  const [shareOpen, setShareOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);

  useEffect(() => { localStorage.setItem("cc_count", JSON.stringify(count)); }, [count]);
  useEffect(() => { localStorage.setItem("cc_posts", JSON.stringify(posts)); }, [posts]);

  // apply tweaks to CSS vars
  useEffect(() => {
    const r = document.documentElement.style;
    const [a, b, c] = t.accents;
    r.setProperty("--neon-magenta", a);
    r.setProperty("--neon-purple", b);
    r.setProperty("--neon-cyan", c);
    r.setProperty("--glass-blur", t.glass + "px");
    r.setProperty("--font-display", TYPEFACES[t.typeface] || TYPEFACES.Moderna);
    const rad = RADII[t.radius] || 22;
    r.setProperty("--r-lg", rad - 2 + "px");
    r.setProperty("--r-md", rad - 8 + "px");
    document.querySelector(".ambient").style.opacity = (t.glow / 100);
  }, [t]);

  const accessoriesTotal = (acc) => (acc || []).reduce((s, id) => s + (CC.accessories.find((a) => a.id === id)?.price || 0), 0);
  const livePrice = (model ? model.price : 0) + accessoriesTotal(design.accessories);

  const nav = (s) => { setSection(s); window.scrollTo({ top: 0, behavior: "smooth" }); };

  const pickModel = (m) => {
    setModel(m);
    setDesign({ base: "#1b1740", pattern: "none", design: null, texts: [], images: [], accessories: [] });
    nav("editor");
  };
  const usePreset = (d) => {
    setModel(model || CC.models[0]);
    setDesign({ base: "#1b1740", pattern: "none", design: null, img: d.img || null, texts: [], images: [], accessories: [] });
    nav("editor");
  };
  const addAccessoryToCart = (a) => {
    setCart((c) => [...c, { id: "acc-" + Date.now(), modelId: null, name: a.name, accessoryOnly: true, design: { base: "#1b1740" }, accessories: [a.id], price: a.price }]);
  };
  const addToCart = () => {
    setCart((c) => [...c, { id: "case-" + Date.now(), modelId: model.id, design: JSON.parse(JSON.stringify(design)), accessories: design.accessories || [], price: livePrice }]);
    setCartOpen(true);
  };
  const removeFromCart = (id) => setCart((c) => c.filter((x) => x.id !== id));
  const checkout = () => { setCount((n) => n + cart.filter((i) => !i.accessoryOnly).length || n + 1); setCart([]); };
  const deletePost = (id) => { setPosts((p) => p.filter((x) => x.id !== id)); setCount((n) => Math.max(3000, n - 1)); };
  const publishPost = ({ caption, backdrop }) => {
    const post = { id: "u" + Date.now(), user: "@tú", modelId: model.id, design: JSON.parse(JSON.stringify(design)), caption, likes: 1, backdrop, fromPurchase: true };
    setPosts((p) => [post, ...p]);
    setCount((n) => n + 1);
  };

  return (
    <>
      <LiquidBar section={section} onNav={nav} cartCount={cart.length} onCart={() => setCartOpen(true)} />

      {section === "home" && <HomeView onPick={pickModel} />}
      {section === "editor" && model && <EditorView model={model} design={design} setDesign={setDesign} onBack={() => nav("home")} onAddToCart={addToCart} onShare={() => setShareOpen(true)} livePrice={livePrice} />}
      {section === "designs" && <DesignsView onUse={usePreset} />}
      {section === "accessories" && <AccessoriesView onAddAccessory={addAccessoryToCart} />}
      {section === "offers" && <OffersView />}
      {section === "community" && <CommunityView count={count} posts={posts} onFollow={() => window.open("https://instagram.com/cool.case.cl", "_blank")} onDeletePost={deletePost} />}

      {shareOpen && model && <ShareModal model={model} design={design} onClose={() => setShareOpen(false)} onPublish={publishPost} />}
      {cartOpen && <CartModal items={cart} onClose={() => setCartOpen(false)} onCheckout={checkout} onRemove={removeFromCart} />}

      <TweaksPanel>
        <TweakSection label="Estilo visual" />
        <TweakColor label="Acentos neón" value={t.accents}
          options={[["#ff3df0","#8b5cff","#2de2ff"],["#ff5ec4","#ffb24d","#3dffa8"],["#2de2ff","#3dffa8","#8b5cff"],["#ff3df0","#2de2ff","#ffffff"]]}
          onChange={(v) => setTweak("accents", v)} />
        <TweakSlider label="Intensidad vidrio" value={t.glass} min={6} max={40} unit="px" onChange={(v) => setTweak("glass", v)} />
        <TweakSlider label="Resplandor ambiente" value={t.glow} min={20} max={140} unit="%" onChange={(v) => setTweak("glow", v)} />
        <TweakSection label="Tipografía" />
        <TweakRadio label="Titulares" value={t.typeface} options={["Moderna","Editorial","Técnica"]} onChange={(v) => setTweak("typeface", v)} />
        <TweakSection label="Forma" />
        <TweakRadio label="Esquinas" value={t.radius} options={["Mancha","Burbuja","Cápsula"]} onChange={(v) => setTweak("radius", v)} />
      </TweaksPanel>
    </>
  );
}

// Root: puerta de acceso a la muestra + ruteo. #admin abre el panel de administración.
function Root() {
  const [route, setRoute] = useState(window.location.hash.replace(/^#/, ""));
  useEffect(() => {
    const on = () => setRoute(window.location.hash.replace(/^#/, ""));
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return (
    <AccessGate>
      {route === "admin" ? <AdminApp /> : <App />}
    </AccessGate>
  );
}

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