// Home screen sections + App router
const Header = window.Header;
const Hero = window.Hero;
const Catalog = window.Catalog;
const Product = window.Product;
const ProductCard = window.ProductCard;
const CartDrawer = window.CartDrawer;
const DMOrder = window.DMOrder;
const Footer = window.Footer;
const Ic = window.Ic;

function SkeletonCard() {
  return (
    <div style={{ background:"#F2F1F3", borderRadius:16, overflow:"hidden" }}>
      <div style={{ aspectRatio:"1/1", background:"#E8E7E9" }}/>
      <div style={{ padding:"14px 16px 16px", display:"flex", flexDirection:"column", gap:8 }}>
        <div style={{ height:10, width:"40%", background:"#E8E7E9", borderRadius:4 }}/>
        <div style={{ height:14, width:"75%", background:"#E8E7E9", borderRadius:4 }}/>
        <div style={{ height:12, width:"55%", background:"#E8E7E9", borderRadius:4 }}/>
        <div style={{ height:16, width:"35%", background:"#E8E7E9", borderRadius:4, marginTop:4 }}/>
      </div>
    </div>
  );
}

function FeaturedStrip({ products, loading, onOpen, onNav, eyebrow, title, sub }) {
  return (
    <section style={fsStyles.wrap}>
      <div style={fsStyles.head}>
        <div>
          <span style={fsStyles.meta}>{eyebrow}</span>
          <h2 style={fsStyles.title}>{title}</h2>
          {sub && <p style={fsStyles.sub}>{sub}</p>}
        </div>
        <a style={fsStyles.viewAll} onClick={() => onNav && onNav("catalog")}>View all <Ic.Arrow size={14}/></a>
      </div>
      <div style={fsStyles.grid} className="prod-grid">
        {loading && products.length === 0
          ? [0,1,2,3].map(i => <SkeletonCard key={i}/>)
          : products.map(p => <ProductCard key={p.id} p={p} onOpen={onOpen}/>)
        }
      </div>
    </section>
  );
}

const fsStyles = {
  wrap: { maxWidth:1280, margin:"0 auto", padding:"40px 24px" },
  head: { display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom:18 },
  meta: { fontFamily:"JetBrains Mono, monospace", fontSize:11, letterSpacing:"0.18em", textTransform:"uppercase", color:"#8A8990" },
  title: { margin:"6px 0 6px", fontFamily:"Inter, sans-serif", fontWeight:900, fontSize:56, lineHeight:0.95, letterSpacing:"-0.035em", textTransform:"uppercase", color:"#0E0D11" },
  sub: { margin:0, fontFamily:"Inter, sans-serif", fontSize:15, color:"#4A4852" },
  viewAll: { fontFamily:"Inter, sans-serif", fontWeight:500, fontSize:14, color:"#0E0D11", display:"inline-flex", alignItems:"center", gap:6, textDecoration:"underline", textUnderlineOffset:4, cursor:"pointer" },
  grid: { display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:18 },
};

// Editorial reels block — full bleed dark photo strip with overlay text
function ReelsBlock() {
  const mob = typeof window !== "undefined" && window.innerWidth < 768;
  return (
    <section style={{ padding: mob ? "16px 16px" : "40px 24px", maxWidth:1280, margin:"0 auto" }}>
      <div style={{
        position:"relative", borderRadius: mob ? 18 : 24, overflow:"hidden",
        padding: mob ? "28px 22px 80px" : "56px 56px 96px",
        minHeight: mob ? 260 : 380,
        background:
          "linear-gradient(180deg, rgba(0,0,0,0.0) 30%, rgba(0,0,0,0.65) 100%), " +
          "radial-gradient(80% 100% at 30% 30%, #4f5a8a 0%, #1a1c2e 60%, #0E0D11 100%)",
      }}>
        <span style={rbStyles.meta}>/ REELS · @nine.ub9 /</span>
        <div style={{
          ...rbStyles.headline,
          fontSize: mob ? 32 : 64,
          marginTop: mob ? 12 : 18,
          lineHeight: mob ? 1.1 : 1.0,
        }}>
          <span style={{background:"#FFEC42",color:"#0E0D11",padding:"0 0.15em"}}>Wired</span> чихэвч<br/>
          2026 онд яагаад<br/>
          дахин <span style={{background:"#FF3B6F",color:"#fff",padding:"0 0.15em"}}>cool</span> болов?
        </div>
        <div style={{
          position:"absolute",
          left: mob ? 22 : 56,
          right: mob ? 22 : 56,
          bottom: mob ? 22 : 36,
          display:"flex", justifyContent:"space-between", alignItems:"center",
        }}>
          <a href="https://www.instagram.com/p/DW8vgpFkxoU/" target="_blank" rel="noopener noreferrer" style={{
            ...rbStyles.btn,
            padding: mob ? "10px 14px" : "13px 18px",
            fontSize: mob ? 13 : 14,
          }}>Watch reel <Ic.Play size={12}/></a>
          <span style={{ ...rbStyles.handle, fontSize: mob ? 12 : 14 }}><Ic.Insta size={mob ? 14 : 16}/> @nine.ub9</span>
        </div>
      </div>
    </section>
  );
}

const rbStyles = {
  meta: { fontFamily:"JetBrains Mono, monospace", fontSize:11, letterSpacing:"0.18em", textTransform:"uppercase", color:"rgba(255,255,255,0.8)" },
  headline: { fontFamily:"Inter, sans-serif", fontWeight:900, letterSpacing:"-0.03em", textTransform:"uppercase", color:"#fff", textShadow:"0 2px 8px rgba(0,0,0,0.4)" },
  btn: { background:"#fff", color:"#0E0D11", borderRadius:12, fontFamily:"Inter, sans-serif", fontWeight:600, textDecoration:"none", display:"inline-flex", alignItems:"center", gap:8, cursor:"pointer" },
  handle: { color:"#fff", fontFamily:"Inter, sans-serif", display:"inline-flex", alignItems:"center", gap:6 },
};

window.FeaturedStrip = FeaturedStrip;
window.ReelsBlock = ReelsBlock;

// Wired editorial banner — placed below −50% OR GONE section
function WiredBanner({ onShop }) {
  return (
    <section style={{ maxWidth:1280, margin:"0 auto", padding:"0 24px 80px" }}>
      <div style={{ position:"relative", borderRadius:28, overflow:"hidden", cursor:"pointer" }} onClick={onShop}>
        <img
          src="assets/wired-banner.png"
          style={{ width:"100%", display:"block", borderRadius:28, maxHeight:360, objectFit:"cover", objectPosition:"center" }}
          loading="lazy" decoding="async" width="1280" height="360"
        />
        <div style={{ position:"absolute", bottom:28, right:32 }}>
          <button onClick={onShop} style={{ display:"inline-flex", alignItems:"center", gap:10, background:"#1F1D23", color:"#fff", border:"none", padding:"14px 22px", borderRadius:12, fontFamily:"Inter, sans-serif", fontWeight:600, fontSize:15, cursor:"pointer" }}>
            Shop now <Ic.Arrow size={14}/>
          </button>
        </div>
      </div>
    </section>
  );
}

window.WiredBanner = WiredBanner;

function DownloadGuide() {
  const mob = typeof window !== "undefined" && window.innerWidth < 768;
  const btnBase = { display:"flex", alignItems:"center", justifyContent:"center", gap:8, borderRadius:14, fontFamily:"Inter, sans-serif", fontWeight:800, textDecoration:"none", letterSpacing:"-0.01em", width: mob ? "100%" : "auto", padding: mob ? "16px 20px" : "16px 36px", fontSize: mob ? 19 : 20, boxSizing:"border-box" };
  return (
    <section style={{ background:"linear-gradient(180deg,#FFFFFF 0%,#C9C8CE 100%)", padding: mob ? "36px 20px 44px" : "56px 24px" }}>
      <div style={{ maxWidth:1280, margin:"0 auto", textAlign:"center" }}>
        <span style={{ fontFamily:"JetBrains Mono, monospace", fontSize:11, letterSpacing:"0.18em", textTransform:"uppercase", color:"#8A8990" }}>/ ЗААВАР /</span>
        <h2 style={{ fontFamily:"Inter, sans-serif", fontWeight:900, fontSize: mob ? 40 : 64, letterSpacing:"-0.04em", textTransform:"uppercase", color:"#0E0D11", margin:"10px 0 10px", lineHeight:1.0 }}>
          ХЭРХЭН ДУУГАА<br/>ТАТАХ ВЭ?
        </h2>
        <p style={{ fontFamily:"Inter, sans-serif", fontSize: mob ? 13 : 16, color:"#4A4852", margin:"0 0 28px", letterSpacing:"0.02em" }}>
          ТА ДООРХ LINK ДЭЭР ДАРААД ЗААВАР АВААРАЙ
        </p>
        <div style={{ display:"flex", flexDirection: mob ? "column" : "row", gap: mob ? 12 : 14, justifyContent:"center", alignItems:"center", maxWidth: mob ? 360 : "none", margin:"0 auto" }}>
          <a href="https://www.instagram.com/p/DYH97NNTCYU/?hl=en" target="_blank" rel="noopener noreferrer" style={{ ...btnBase, background:"#0E0D11", color:"#fff" }}>
            MP4 ТАТАХ ЗААВАР
          </a>
          <a href="https://www.instagram.com/p/DYgw2WUTvbT/?hl=en" target="_blank" rel="noopener noreferrer" style={{ ...btnBase, background:"#FFEC42", color:"#0E0D11" }}>
            MP4 ДЭЭР БИЧЛЭГ ТАТАХ ЗААВАР
          </a>
          <a href="https://drive.google.com/drive/folders/1NNB0tv7T7lIxr_nlFBecia2Ur87rRfwj?usp=drive_link" target="_blank" rel="noopener noreferrer" style={{ ...btnBase, background:"#FF6A30", color:"#fff" }}>
            IPOD NANO 3-Т КЛИПТЭЙ ДУУ ТАТАХ ЗААВАР
          </a>
          <a href="https://drive.google.com/drive/folders/1IqsAI1zKqcufDhEECKcG9Q7ynLnVKOtK?usp=sharing" target="_blank" rel="noopener noreferrer" style={{ ...btnBase, background:"#2563EB", color:"#fff" }}>
            УТАСНААСАА IPOD NANO 3 РУУ ДУУ ТАТАХ ЗААВАР
          </a>
          <a href="https://drive.google.com/drive/folders/1hk91oQH_hwLLRTHIIXgtxiI6RnsjlAJf?usp=drive_link" target="_blank" rel="noopener noreferrer" style={{ ...btnBase, background:"#0E0D11", color:"#fff" }}>
            ↓ ПРОГРАМ ТАТАЖ АВАХ
          </a>
        </div>
      </div>
    </section>
  );
}

window.DownloadGuide = DownloadGuide;

// ============================================================
// App root — manages screen + cart state
// ============================================================
function App() {
  const [screen, setScreen] = React.useState("home"); // home | catalog | product
  const [catFilter, setCatFilter] = React.useState("All");
  const [searchQuery, setSearchQuery] = React.useState("");
  const [activeProduct, setActiveProduct] = React.useState(null);
  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);

  const navigate = (s, cat) => {
    setScreen(s);
    if (cat) setCatFilter(cat);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  const handleSearch = q => {
    setSearchQuery(q);
    if (q.trim()) {
      setScreen("catalog");
      setCatFilter("All");
      window.scrollTo({ top: 0, behavior: "instant" });
    }
  };

  const openProduct = (p) => { setActiveProduct(p); setScreen("product"); window.scrollTo({top:0, behavior:"instant"}); };
  const addToCart = (p, color, qty) => {
    setCart([...cart, { ...p, color, qty }]);
    setCartOpen(true);
  };
  const changeQty = (i, q) => {
    if (q < 1) return setCart(cart.filter((_,j) => j !== i));
    setCart(cart.map((it,j) => j===i ? {...it, qty: q} : it));
  };

  const [productsLoading, setProductsLoading] = React.useState(true);

  const [products, setProducts] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("n9_admin_products"));
      if (saved && saved.length) {
        const valid = saved.filter(p => p && p.name && p.price && typeof p.id === "string");
        if (valid.length) return valid;
      }
    } catch(e) {}
    return [];
  });

  const [cats, setCats] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("n9_admin_cats"));
      if (saved && saved.length) return saved;
    } catch(e) {}
    return window.N9_CATEGORIES || ["All", "iPod", "MP4"];
  });

  React.useEffect(() => {
    fetch("/api/get-products?t=" + Date.now())
      .then(r => r.json())
      .then(data => {
        if (data && data.length) {
          setProducts(data);
          localStorage.setItem("n9_admin_products", JSON.stringify(data));
        }
      })
      .catch(() => {})
      .finally(() => setProductsLoading(false));
    fetch("/api/get-categories")
      .then(r => r.json())
      .then(data => {
        if (data && data.length) {
          setCats(data);
          localStorage.setItem("n9_admin_cats", JSON.stringify(data));
          window.N9_CATEGORIES = data;
        }
      })
      .catch(() => {});
  }, []);

  return (
    <div>
      <Header cartCount={cart.reduce((s,i)=>s+i.qty,0)} onNav={navigate} onOpenCart={()=>setCartOpen(true)} onSearch={handleSearch} screen={screen}/>
      {screen === "home" && (
        <main>
          <Hero onShop={() => navigate("catalog","All")}/>
          <FeaturedStrip
            products={products}
            loading={productsLoading}
            onOpen={openProduct}
            onNav={navigate}
            eyebrow="/ ШИНЭ DROP · 09 ДЭХ 7 ХОНОГ /"
            title="БУСДААС ТҮРҮҮЛ."
            sub=""
          />
          <ReelsBlock/>
          <FeaturedStrip
            products={products.filter(p => p.sale).slice(0,4)}
            onOpen={openProduct}
            onNav={navigate}
            eyebrow="/ SALE · ENDING SOON /"
            title="−50% OR GONE."
            sub=""
          />
          <WiredBanner onShop={() => navigate("catalog","All")}/>
          <DownloadGuide/>
        </main>
      )}
      {screen === "catalog" && (
        <Catalog initialCat={catFilter} products={products} onOpen={openProduct} searchQuery={searchQuery} categories={cats}/>
      )}
      {screen === "product" && activeProduct && (
        <Product
          p={activeProduct}
          related={products.filter(x => x.id !== activeProduct.id)}
          onBack={() => navigate("catalog", catFilter)}
          onAdd={addToCart}
          onOpen={openProduct}
        />
      )}
      {screen === "dm" && (
        <DMOrder items={cart} onBack={() => setScreen("home")} couponDiscount={0}/>
      )}
      <Footer/>
      <CartDrawer
        open={cartOpen}
        items={cart}
        onClose={() => setCartOpen(false)}
        onChange={changeQty}
        onDM={() => { setCartOpen(false); setScreen("dm"); window.scrollTo({top:0, behavior:"instant"}); }}
      />
    </div>
  );
}

window.App = App;

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