/* Rass Jerseys - main app */

const TWEAK_DEFAULTS = {
  accent: "#FFD60A",
  roundness: 14,
  shadow: "soft",
};

let _cartId = 0;
function newCartId() { return "ci-" + (++_cartId); }

function SearchOverlay({ onClose, onOpen }) {
  const [q, setQ] = React.useState("");
  const ref = React.useRef(null);
  React.useEffect(() => { if (ref.current) ref.current.focus(); }, []);
  const query = q.toLowerCase();
  const hits = query
    ? RassData.PRODUCTS.filter((product) => {
        const team = RassData.teamById(product.team);
        return (team.name + " " + product.type + " " + product.name).toLowerCase().includes(query);
      })
    : RassData.PRODUCTS;

  return (
    <div className="search-overlay" onClick={onClose}>
      <div className="search-box" onClick={(e) => e.stopPropagation()}>
        <div className="search-field">
          <Icon name="search" size={20} style={{ color: "var(--text-2)" }} />
          <input ref={ref} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search jerseys..." />
          <button className="nav-icon" style={{ width: 34, height: 34 }} onClick={onClose}>
            <Icon name="close" size={18} />
          </button>
        </div>
        {!q && <div className="search-hint">All kits</div>}
        <div className="search-results">
          {hits.map((product) => {
            const team = RassData.teamById(product.team);
            return (
              <button key={product.id} className="search-hit" onClick={() => { onOpen(product); onClose(); }}>
                <JerseyPlaceholder product={product} ratio="1/1" style={{ width: 46, height: 46, borderRadius: 9, flex: "none" }} />
                <span style={{ flex: 1 }}>
                  <span className="search-hit-name">{team.name} {product.type}</span>
                </span>
                <span className="price" style={{ fontSize: 16 }}>{RassData.taka(product.price)}</span>
              </button>
            );
          })}
          {hits.length === 0 && <div className="search-hint">No jerseys match "{q}".</div>}
        </div>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [loading, setLoading] = React.useState(true);
  const [route, setRoute] = React.useState({ name: "home" });
  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [orderPrompt, setOrderPrompt] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const [, forceRefresh] = React.useState(0);
  const gridRef = React.useRef(null);
  const aboutRef = React.useRef(null);

  React.useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent);
    root.style.setProperty("--r-card", t.roundness + "px");
    root.style.setProperty("--r-btn", Math.max(4, Math.round(t.roundness * 0.62)) + "px");
    const shadows = {
      flat: ["0 1px 3px rgba(16,40,30,.06)", "0 4px 12px rgba(16,40,30,.08)"],
      soft: ["0 2px 16px rgba(16,40,30,.07)", "0 14px 40px rgba(16,40,30,.14)"],
      bold: ["0 6px 22px rgba(16,40,30,.12)", "0 22px 54px rgba(16,40,30,.2)"],
    };
    const pair = shadows[t.shadow] || shadows.soft;
    root.style.setProperty("--shadow", pair[0]);
    root.style.setProperty("--shadow-lg", pair[1]);
  }, [t.accent, t.roundness, t.shadow]);

  React.useEffect(() => {
    let cancelled = false;
    (async function bootstrap() {
      try {
        const [metaResult, productResult] = await Promise.all([
          RassApi.meta(),
          RassApi.storeProducts(),
        ]);
        if (cancelled) return;
        RassData.setStore(metaResult.store);
        RassData.setProducts(productResult.products || []);
        forceRefresh((value) => value + 1);
      } catch (error) {
        console.error(error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const goHome = () => {
    setRoute({ name: "home" });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const openDetail = (product) => setRoute({ name: "detail", id: product.id });

  const cartCount = cart.reduce((sum, item) => sum + item.qty, 0);

  const addToCart = (item) => {
    const names = Array.isArray(item.customNames) ? item.customNames : [];
    const hasNames = names.length > 0;
    setCart((prev) => {
      // Only merge unnamed lines; lines with custom names stay distinct.
      const existing = !hasNames && prev.find((row) =>
        row.productId === item.productId && row.size === item.size && (row.customNames || []).length === 0);
      if (existing) {
        return prev.map((row) => row.id === existing.id ? { ...row, qty: row.qty + item.qty } : row);
      }
      return prev.concat({ ...item, customNames: hasNames ? RassData.resizeNames(names, item.qty) : [], id: newCartId() });
    });
    const product = RassData.productById(item.productId);
    const team = RassData.teamById(product.team);
    setToast(team.name + " " + product.type + " added to cart.");
  };

  const updateCartItem = (id, patch) => {
    setCart((prev) => prev.map((item) => item.id === id ? { ...item, ...patch } : item));
  };

  const removeCartItem = (id) => {
    setCart((prev) => prev.filter((item) => item.id !== id));
  };

  const scrollTo = (ref) => {
    if (route.name !== "home") {
      setRoute({ name: "home" });
      setTimeout(() => ref.current && ref.current.scrollIntoView({ block: "start" }), 80);
      return;
    }
    if (ref.current) ref.current.scrollIntoView({ block: "start" });
  };

  if (loading) {
    return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: "var(--f-head)" }}>Loading store...</div>;
  }

  const activeProduct = route.name === "detail" ? RassData.productById(route.id) : null;

  return (
    <React.Fragment>
      <Navbar
        onHome={goHome}
        onShop={() => scrollTo(gridRef)}
        onAbout={() => scrollTo(aboutRef)}
        onSearch={() => setRoute((r) => ({ ...r, search: true }))}
        onCart={() => setCartOpen(true)}
        cartCount={cartCount}
      />

      {route.name === "home" || !activeProduct ? (
        <main>
          <Hero onShop={() => scrollTo(gridRef)} />
          <TrustBar />
          <ProductGrid onOpen={openDetail} innerRef={gridRef} />
          <JerseyQuality />
          <HappyCustomers />
          <div ref={aboutRef}><HowItWorks /></div>
        </main>
      ) : (
        <DetailView product={activeProduct} onBack={goHome} onAddToCart={(item) => { addToCart(item); setCartOpen(true); }} />
      )}

      <Footer onHome={goHome} onShop={() => scrollTo(gridRef)} />

      {cartOpen && (
        <CartDrawer
          cart={cart}
          onUpdate={updateCartItem}
          onRemove={removeCartItem}
          onClose={() => setCartOpen(false)}
          onCheckout={() => { setCartOpen(false); setOrderPrompt(true); }}
        />
      )}

      {orderPrompt && (
        <OrderPromptModal
          cart={cart}
          onClose={() => setOrderPrompt(false)}
        />
      )}

      {route.search && (
        <SearchOverlay
          onClose={() => setRoute((r) => ({ ...r, search: false }))}
          onOpen={(product) => setRoute({ name: "detail", id: product.id })}
        />
      )}

      {toast && <CartToast message={toast} onDone={() => setToast(null)} />}

      <TweaksPanel>
        <TweakSection label="Style" />
        <TweakColor label="Accent" value={t.accent}
          options={["#FFD60A", "#52B788", "#FF8A3D", "#2A9DF4", "#E84855"]}
          onChange={(value) => setTweak("accent", value)} />
        <TweakSlider label="Corner radius" value={t.roundness} min={4} max={24} step={1}
          unit="px" onChange={(value) => setTweak("roundness", value)} />
        <TweakRadio label="Shadow" value={t.shadow}
          options={[{ value: "flat", label: "Flat" }, { value: "soft", label: "Soft" }, { value: "bold", label: "Bold" }]}
          onChange={(value) => setTweak("shadow", value)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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