// Furnishfy — main app: router, tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "direction": "sapphire",
    "gold": window.FURN?.PRIMARY_COLOR || "#fd6221",
    "secondary": window.FURN?.SECONDARY_COLOR || "#2c2c2c",
    "radius": 4,
    "displayFont": "Cormorant Garamond"
}/*EDITMODE-END*/;

// ---------- Search overlay ----------
function SearchOverlay({ open, onClose, go }) {
    const [q, setQ] = useState("");
    const { PRODUCTS } = window.FURN;
    const inputRef = useRef(null);
    useEffect(() => { if (open) { setQ(""); setTimeout(() => inputRef.current?.focus(), 80); } }, [open]);
    const res = q.trim() ? PRODUCTS.filter((p) => (p.en + p.material.en).toLowerCase().includes(q.toLowerCase())).slice(0, 5) : [];
    return (
        <div style={{ position: "fixed", inset: 0, zIndex: 90, opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .35s" }}>
            <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "oklch(0.1 0.02 258 / .8)", backdropFilter: "blur(8px)" }} />
            <div style={{ position: "relative", maxWidth: 720, margin: "0 auto", paddingTop: "14vh", padding: "14vh 24px 0" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 16, borderBottom: "1px solid var(--gold)", paddingBottom: 18 }}>
                    <Icon name="search" size={26} style={{ color: "var(--gold)" }} />
                    <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search the collection..."
                        style={{ flex: 1, background: "none", border: "none", outline: "none", color: "var(--ink)", fontFamily: "var(--font-display)", fontSize: "clamp(24px,4vw,38px)" }} />
                    <button className="icon-btn" onClick={onClose}><Icon name="close" size={26} /></button>
                </div>
                <div style={{ marginTop: 10 }}>
                    {res.map((p) => {
                        const hasImg = p.thumbnail && !p.thumbnail.includes('no-product');
                        return (
                            <div key={p.id} onClick={() => { onClose(); go("product", p.id); }} style={{ display: "flex", alignItems: "center", gap: 18, padding: "16px 4px", borderBottom: "1px solid var(--line)", cursor: "pointer" }} className="searchres">
                                {hasImg ? (
                                    <img src={p.thumbnail} alt={p.en} style={{ width: 56, height: 64, flexShrink: 0, borderRadius: 3, objectFit: "cover" }} />
                                ) : (
                                    <Placeholder hue={p.hue} label="" style={{ width: 56, height: 64, flexShrink: 0, borderRadius: 3 }} />
                                )}
                                <div style={{ flex: 1 }}>
                                    <div style={{ fontFamily: "var(--font-display)", fontSize: 20 }}>{p.en}</div>
                                    <div style={{ color: "var(--faint)", fontSize: 13 }}>{p.material.en}</div>
                                </div>
                                <div style={{ color: "var(--gold)" }}>{money(p.price)}</div>
                            </div>
                        );
                    })}
                    {q.trim() && res.length === 0 && <p style={{ color: "var(--muted)", padding: "24px 4px", fontSize: 15 }}>No results found.</p>}
                </div>
            </div>
            <style>{`.searchres{ transition: background .25s; } .searchres:hover{ background: var(--surface); }`}</style>
        </div>
    );
}

// ---------- Story page ----------
function Story({ go }) {
    useReveal();
    return (
        <main className="page-fade" style={{ paddingTop: 92 }}>
            <section className="wrap" style={{ padding: "80px 40px 50px", textAlign: "center" }}>
                <div className="eyebrow" style={{ justifyContent: "center" }}>The Atelier</div>
                <h1 style={{ fontSize: "clamp(40px,7vw,92px)", margin: "20px auto 0", maxWidth: 900 }}>
                    We build as if time stands still.
                </h1>
                <p style={{ color: "var(--muted)", fontSize: 18, lineHeight: 1.8, maxWidth: 620, margin: "26px auto 0" }}>
                    Since 1988, we have gathered the finest makers around a single bench — choosing timber by hand and refusing anything disposable.
                </p>
            </section>
            <section className="wrap" style={{ padding: "10px 40px 40px" }}>
                <Placeholder hue={45} name="Inside the atelier" label="atelier film still" style={{ aspectRatio: "21/9", borderRadius: var_radius3(), border: "1px solid var(--line)" }} />
            </section>
            <section className="wrap grid-3" style={{ padding: "50px 40px 110px" }}>
                {[["Hand-selected", "We travel to the mills ourselves and reject 9 of every 10 boards."],
                ["Slow-finished", "Each surface is oiled and rubbed over twelve patient days."],
                ["Built to repair", "Joinery is designed to be opened, mended, and passed on."]].map((b, i) => (
                    <div key={i} className="reveal" style={{ transitionDelay: i * 80 + "ms" }}>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--gold)" }}>{b[0]}</div>
                        <p style={{ color: "var(--muted)", fontSize: 15.5, lineHeight: 1.75, marginTop: 12 }}>{b[1]}</p>
                    </div>
                ))}
            </section>
            <section className="wrap" style={{ padding: "0 40px 110px", textAlign: "center" }}>
                <button className="btn btn--solid" onClick={() => go("shop")}><span>Explore collection <Icon name="arrow" size={16} /></span></button>
            </section>
        </main>
    );
}
function var_radius3() { return getComputedStyle(document.documentElement).getPropertyValue("--radius") || "4px"; }

const { BrowserRouter, Routes, Route, useNavigate, useParams, useSearchParams, useLocation } = window.ReactRouterDOM;

function ShopWrapper({ go, lang }) {
    const [searchParams] = useSearchParams();
    const cat = searchParams.get("cat") || null;
    return <Shop go={go} initialCat={cat} lang={lang} />;
}

function ProductWrapper({ go, lang }) {
    const { productId } = useParams();
    return <Product go={go} productId={productId} lang={lang} />;
}

// ---------- AppContent ----------
function AppContent() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const [searchOpen, setSearchOpen] = useState(false);
    const [lang, setLang] = useState("en");
    const navigate = useNavigate();
    const location = useLocation();

    // apply tweaks → root
    useEffect(() => {
        const r = document.documentElement;
        r.setAttribute("data-theme", t.direction);
        r.style.setProperty("--gold", t.gold);
        r.style.setProperty("--secondary", t.secondary || "#2c2c2c");
        r.style.setProperty("--radius", t.radius + "px");
        r.style.setProperty("--font-display", `"${t.displayFont}", Georgia, serif`);
    }, [t]);

    const go = useCallback((p, id = null, cat = null) => {
        if (p !== "product") window.scrollTo({ top: 0, behavior: "instant" });
        if (p === "home") {
            navigate("/");
        } else if (p === "shop") {
            navigate(cat ? `/shop?cat=${cat}` : "/shop");
        } else if (p === "rooms") {
            navigate(cat ? `/rooms?cat=${cat}` : "/rooms");
        } else if (p === "product") {
            navigate(`/product/${id}`);
        } else {
            navigate(`/${p}`);
        }
    }, [navigate]);

    // Active page determination for header active state highlighting
    let activePage = "home";
    const path = location.pathname;
    if (path.startsWith("/shop")) activePage = "shop";
    else if (path.startsWith("/rooms")) activePage = "rooms";
    else if (path.startsWith("/product")) activePage = "product";
    else if (path.startsWith("/story")) activePage = "story";
    else if (path.startsWith("/contact")) activePage = "contact";

    return (
        <>
            <Header page={activePage} go={go} openSearch={() => setSearchOpen(true)} lang={lang} />

            <Routes>
                <Route path="/" element={<Home go={go} lang={lang} />} />
                <Route path="/shop" element={<ShopWrapper go={go} lang={lang} />} />
                <Route path="/rooms" element={<ShopWrapper go={go} lang={lang} />} />
                <Route path="/product/:productId" element={<ProductWrapper go={go} lang={lang} />} />
                <Route path="/story" element={<Story go={go} lang={lang} />} />
                <Route path="/contact" element={<Contact go={go} lang={lang} />} />
            </Routes>

            <Footer go={go} lang={lang} />

            <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} go={go} />

            <TweaksPanel title="Tweaks">
                <TweakSection label="Design direction" />
                <TweakRadio label="Theme" value={t.direction}
                    options={[{ value: "sapphire", label: "Sapphire" }, { value: "emerald", label: "Emerald" }]}
                    onChange={(v) => setTweak("direction", v)} />
                <TweakColor label="Accent" value={t.gold}
                    options={["#C9A24B", "#D7B66A", "#B98E3C", "#CBB892"]}
                    onChange={(v) => setTweak("gold", v)} />
                <TweakSection label="Form" />
                <TweakSlider label="Corner radius" value={t.radius} min={0} max={18} unit="px"
                    onChange={(v) => setTweak("radius", v)} />
                <TweakSelect label="Display font" value={t.displayFont}
                    options={["Cormorant Garamond", "Jost"]}
                    onChange={(v) => setTweak("displayFont", v)} />
            </TweaksPanel>
        </>
    );
}

// ---------- App ----------
function App() {
    return (
        <BrowserRouter>
            <AppContent />
        </BrowserRouter>
    );
}

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