/* eslint-disable */
const { useState, useMemo, useEffect, useRef } = React;

// ============================================================
// TopBar
// ============================================================
const UTILITY_PROMOS = [
  { tag: "OFFER", text: "Trade accounts · 10% off first order with code BENCH10" },
  { tag: "NEW",   text: "Workshop manuals & torque-spec cards now stocked" },
  { tag: "FAST",  text: "Order before 5pm · UK-wide delivery in 24 hrs" },
];

// Mobile dept nav: full list with display labels + filter keys.
// Single source of truth, also used by the slide-down menu on small screens.
const DEPT_LINKS = [
  { label: "Oil & filters", filter: "Oil & filters" },
  { label: "Brakes",        filter: "Brake parts" },
  { label: "Tyres",         filter: "Tyres" },
  { label: "Lighting",      filter: "Bulbs / lighting" },
  { label: "Wipers",        filter: "Wiper & screenwash items" },
  { label: "Batteries",     filter: "Batteries" },
  { label: "Suspension",    filter: "Suspension parts" },
  { label: "Ignition",      filter: "Ignition/service ignition parts" },
  { label: "Belts",         filter: "Belts & pulleys" },
  { label: "Exhaust",       filter: "Exhaust / emissions parts" },
];

function TopBar({ route, navigate, shop, openCart, openGarage }) {
  const [searchCat, setSearchCat] = useState("All categories");
  const [searchQ, setSearchQ] = useState("");
  const [acOpen, setAcOpen] = useState(false);
  const [promoI, setPromoI] = useState(0);
  const [supportOpen, setSupportOpen] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const searchRef = useRef(null);
  const supportRef = useRef(null);
  const fitment = shop.activeVehicle;

  // Click-outside closes both popovers (search autocomplete + support menu)
  useEffect(() => {
    const onClick = (e) => {
      if (searchRef.current && !searchRef.current.contains(e.target)) setAcOpen(false);
      if (supportRef.current && !supportRef.current.contains(e.target)) setSupportOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  // Rotate the inline utility-bar promo slot every 5s.
  useEffect(() => {
    const t = setInterval(() => setPromoI(x => (x + 1) % UTILITY_PROMOS.length), 5000);
    return () => clearInterval(t);
  }, []);
  const promo = UTILITY_PROMOS[promoI];

  // Compact plate label for the topbar vehicle chip — prefer the raw plate
  // (e.g. "PL15 RXB"), else fall back to a truncated display name.
  const chipLabel = fitment ? (fitment.plate || fitment.value || (fitment.display || "").slice(0, 14)) : "";

  return (
    <>
      {/* Utility strip — status · rotating promo · account links */}
      <div className="utility">
        <div className="shell">
          <div className="utility-left">
            <span><span className="pulse" /> <strong>Open now</strong> · Dispatch by 5pm</span>
            <a><Icons.Phone /> 0808 555 0142</a>
          </div>
          <div className="utility-center" aria-live="polite">
            <span className="utility-promo">
              <span className="promo-tag">{promo.tag}</span>
              <span className="promo-text">{promo.text}</span>
            </span>
            <span className="utility-promo-dots">
              {UTILITY_PROMOS.map((_, k) => (
                <span key={k} className={"udot" + (k === promoI ? " on" : "")} onClick={() => setPromoI(k)} />
              ))}
            </span>
          </div>
          <div className="utility-right">
            <a onClick={() => navigate({ name: "catalog", filter: "Trade deals" })}>Trade deals</a>
            <a>Workshop manuals</a>
            <div className="utility-support" ref={supportRef}>
              <a className="support-trigger" onClick={() => setSupportOpen(o => !o)}>
                Support
                <svg width="8" height="8" viewBox="0 0 8 8" style={{ marginLeft: 4 }} aria-hidden="true">
                  <path d="M1 2.5L4 5.5L7 2.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </a>
              {supportOpen && (
                <div className="support-menu" role="menu">
                  <a className="support-item" onClick={() => setSupportOpen(false)}>Track order</a>
                  <a className="support-item" onClick={() => setSupportOpen(false)}>Help &amp; returns</a>
                </div>
              )}
            </div>
            <a className="utility-globe" title="English · GBP £" aria-label="Language and currency"><Icons.Globe /></a>
            <a><Icons.User style={{width: 12, height: 12}} /> Sign in</a>
          </div>
        </div>
      </div>

      {/* Main topbar */}
      <div className="topbar">
        <div className="shell topbar-main">
          <button
            className="mobile-burger"
            aria-label="Open menu"
            aria-expanded={mobileMenuOpen}
            onClick={() => setMobileMenuOpen(o => !o)}
          >
            <span /><span /><span />
          </button>
          <div className="logo" onClick={() => navigate({ name: "home" })}>
            <div className="logo-mark"><Icons.Tool /></div>
            <div className="logo-text">
              <div className="logo-name">FindCarParts</div>
              <div className="logo-tag">PT.NO LOOKUP · OEM &amp; AFTERMARKET</div>
            </div>
          </div>
          <div className="search" ref={searchRef}>
            <select value={searchCat} onChange={(e) => setSearchCat(e.target.value)}>
              <option>All categories</option>
              <option>Oil &amp; filters</option>
              <option>Brake parts</option>
              <option>Tyres</option>
              <option>Bulbs / lighting</option>
              <option>Wiper &amp; screenwash items</option>
              <option>Batteries</option>
              <option>Suspension parts</option>
              <option>Ignition/service ignition parts</option>
              <option>Belts &amp; pulleys</option>
              <option>Exhaust / emissions parts</option>
            </select>
            <input
              type="text"
              placeholder="Search by part number, brand or description…"
              value={searchQ}
              onChange={(e) => { setSearchQ(e.target.value); setAcOpen(true); }}
              onFocus={() => setAcOpen(true)}
            />
            <button className="search-btn" onClick={() => searchQ && navigate({ name: "catalog" })}>
              <Icons.Search style={{ width: 14, height: 14 }} /> Search
            </button>
            {acOpen && (
              <window.SearchAutocomplete
                query={searchQ}
                navigate={navigate}
                onClose={() => { setAcOpen(false); setSearchQ(""); }}
              />
            )}
          </div>
          <div className="topbar-actions">
            {fitment && (
              <button
                className="tb-veh-chip"
                onClick={openGarage}
                title={`Active vehicle: ${fitment.display}. Click to manage garage.`}
              >
                <Icons.Wheels style={{ width: 14, height: 14 }} />
                <span className="tb-veh-plate">{chipLabel}</span>
                {shop.garage.length > 1 && <span className="tb-veh-more">+{shop.garage.length - 1}</span>}
              </button>
            )}
            <button className="action-btn" onClick={openGarage} title="My garage">
              <Icons.Wheels style={{ width: 20, height: 20 }} />
              <span className="label">Garage</span>
              {shop.garage.length > 0 && <span className="count">{shop.garage.length}</span>}
            </button>
            <button className="action-btn" title="Saved" onClick={() => alert("Saved/Wishlist: " + shop.wishlistItems.map(p => p.name).join(", ") || "Empty")}>
              <Icons.Heart />
              <span className="label">Saved</span>
              {shop.wishlist.length > 0 && <span className="count">{shop.wishlist.length}</span>}
            </button>
            <button className="action-btn" title="Account">
              <Icons.User />
              <span className="label">Account</span>
            </button>
            <button className="action-btn" title="Cart" onClick={openCart}>
              <Icons.Cart />
              <span className="label">Cart</span>
              {shop.cartCount > 0 && <span className="count">{shop.cartCount}</span>}
            </button>
          </div>
        </div>

        {/* Department nav (desktop) */}
        <div className="depts">
          <div className="shell">
            <div className={"dept-link" + (route.name === "catalog" ? " active" : "")} onClick={() => navigate({ name: "catalog" })}>
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M2 3h12M2 8h12M2 13h12" strokeLinecap="round"/></svg>
              Shop all parts
            </div>
            {DEPT_LINKS.map(d => (
              <div key={d.filter} className="dept-link" onClick={() => navigate({ name: "catalog", filter: d.filter })}>{d.label}</div>
            ))}
          </div>
        </div>

        {/* Mobile slide-down menu (replaces dept nav + utility links on small screens) */}
        {mobileMenuOpen && (
          <div className="mobile-menu" role="menu">
            <div className="mm-section">
              <div className="mm-head">Shop</div>
              <button className="mm-item" onClick={() => { navigate({ name: "catalog" }); setMobileMenuOpen(false); }}>
                All parts
              </button>
              {DEPT_LINKS.map(d => (
                <button
                  key={d.filter}
                  className="mm-item"
                  onClick={() => { navigate({ name: "catalog", filter: d.filter }); setMobileMenuOpen(false); }}
                >
                  {d.label}
                </button>
              ))}
            </div>
            <div className="mm-section">
              <div className="mm-head">Account</div>
              <button className="mm-item" onClick={() => { openGarage(); setMobileMenuOpen(false); }}>My garage</button>
              <button className="mm-item">Saved</button>
              <button className="mm-item">Sign in</button>
              <button className="mm-item">Track order</button>
              <button className="mm-item">Help &amp; returns</button>
            </div>
            <div className="mm-section">
              <div className="mm-head">More</div>
              <button className="mm-item" onClick={() => { navigate({ name: "catalog", filter: "Trade deals" }); setMobileMenuOpen(false); }}>Trade deals</button>
              <button className="mm-item">Workshop manuals</button>
              <button className="mm-item">EN · GBP £</button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

// ============================================================
// Footer
// ============================================================
function Footer() {
  const [email, setEmail] = useState("");
  const [sub, setSub] = useState(false);
  return (
    <footer className="footer">
      {/* Newsletter */}
      <div className="newsletter">
        <div className="shell newsletter-inner">
          <div>
            <div className="eyebrow" style={{ color: "var(--yellow)" }}>Trade dispatch</div>
            <h3 className="newsletter-title">Workshop weekly · fitment tips, recalls, deals</h3>
            <p className="newsletter-tag">No spam, no fluff. Real bench-side notes from working mechanics.</p>
          </div>
          <form className="newsletter-form" onSubmit={(e) => { e.preventDefault(); if (email) { setSub(true); setEmail(""); } }}>
            <input type="email" required placeholder="you@workshop.co.uk" value={email} onChange={e => setEmail(e.target.value)} />
            <button className="btn btn-yellow" type="submit">{sub ? "Subscribed ✓" : "Sign me up"}</button>
          </form>
        </div>
      </div>

      <div className="shell footer-top">
        <div className="footer-grid">
          <div>
            <div className="footer-logo">
              <div className="logo-mark"><Icons.Tool style={{ color: "var(--orange)" }} /></div>
              <div className="logo-name">FindCarParts</div>
            </div>
            <p className="footer-tag">A workshop-led parts catalogue. Started by two mechanics who got tired of guessing fitment — now stocked across 12,000+ part numbers.</p>
            <div className="trust-line">
              <span><Icons.Shield style={{ width: 14, height: 14 }} /> 2-year warranty</span>
              <span><Icons.Truck style={{ width: 14, height: 14 }} /> Free over £75</span>
              <span><Icons.Check /> 90-day returns</span>
            </div>
          </div>
          <div>
            <h5>Shop by category</h5>
            <ul>
              <li><a>Oil &amp; filters</a></li>
              <li><a>Brake parts</a></li>
              <li><a>Tyres</a></li>
              <li><a>Bulbs / lighting</a></li>
              <li><a>Batteries</a></li>
              <li><a>Suspension parts</a></li>
            </ul>
          </div>
          <div>
            <h5>Workshop tools</h5>
            <ul>
              <li><a>VIN lookup</a></li>
              <li><a>Reg plate finder</a></li>
              <li><a>Torque values</a></li>
              <li><a>Install guides</a></li>
              <li><a>Cross-reference</a></li>
            </ul>
          </div>
          <div>
            <h5>For trade</h5>
            <ul>
              <li><a>Trade accounts</a></li>
              <li><a>Volume pricing</a></li>
              <li><a>Fleet supply</a></li>
              <li><a>Workshop credit</a></li>
              <li><a>Free same-day collect</a></li>
            </ul>
          </div>
          <div>
            <h5>Support</h5>
            <ul>
              <li><a>Contact support</a></li>
              <li><a>Returns &amp; warranty</a></li>
              <li><a>Order tracking</a></li>
              <li><a>Fitment guarantee</a></li>
              <li><a>FAQ</a></li>
            </ul>
          </div>
        </div>
      </div>
      <div className="shell footer-bottom">
        <span>© MMXXVI · FindCarParts Ltd · Reg. England 09384721</span>
        <div className="links">
          <a>Privacy</a><a>Terms</a><a>Cookies</a><a>Modern Slavery</a>
        </div>
      </div>
    </footer>
  );
}

// ============================================================
// Part card (grid)
// ============================================================
function PartCard({ part, navigate, shop, onQuickView }) {
  const brand = window.PartBrands[part.id] || "OEM";
  const isOEM = part.price > 100;
  const inWishlist = shop && shop.wishlist.includes(part.id);
  const inCompare = shop && shop.compare.includes(part.id);
  const inCart = shop && shop.cart.some(c => c.id === part.id);

  return (
    <div className="part-card" onClick={() => navigate({ name: "detail", id: part.id })}>
      <div className="stage">
        <div className="stage-badges">
          {isOEM && <span className="badge badge-oem">OE-grade</span>}
          {part.rating >= 4.8 && <span className="badge badge-yellow">Top rated</span>}
        </div>
        {shop && (
          <div className="card-tools" onClick={e => e.stopPropagation()}>
            <button className={"card-tool" + (inWishlist ? " on" : "")} onClick={() => shop.toggleWishlist(part.id)} title="Save">
              <Icons.Heart style={{ width: 14, height: 14 }} />
            </button>
            <button className={"card-tool" + (inCompare ? " on" : "")} onClick={() => shop.toggleCompare(part.id)} title="Compare">
              <Icons.Grid style={{ width: 14, height: 14 }} />
            </button>
            {onQuickView && (
              <button className="card-tool" onClick={() => onQuickView(part.id)} title="Quick view">
                <Icons.Search style={{ width: 14, height: 14 }} />
              </button>
            )}
          </div>
        )}
        <div className="stage-sku">{part.sku}</div>
        <div className="stage-3d">3D · Live</div>
        <ThumbViewer part={part} />
      </div>
      <div className="body">
        <div className="cat">{part.category} · {brand}</div>
        <div className="name">{part.name}</div>
        <div className="sub">{part.subtitle}</div>
        <div className="fit"><Icons.Check /> Fits your vehicle</div>
      </div>
      <div className="footer-row">
        <div className="price">
          <span className="cur">£</span>
          <span className="num">{part.price}</span>
          <span className="vat">inc. VAT</span>
        </div>
        <button
          className={"add" + (inCart ? " in-cart" : "")}
          onClick={(e) => { e.stopPropagation(); if (shop) shop.addToCart(part.id, 1); else navigate({ name: "detail", id: part.id }); }}
        >
          {inCart ? <><Icons.Check /> In cart</> : <><Icons.Plus /> Add</>}
        </button>
      </div>
    </div>
  );
}

// ============================================================
// Compact list-view row
// ============================================================
function PartRow({ part, navigate, shop, onQuickView }) {
  const brand = window.PartBrands[part.id] || "OEM";
  const inCart = shop && shop.cart.some(c => c.id === part.id);
  return (
    <div className="row" onClick={() => navigate({ name: "detail", id: part.id })}>
      <div className="mini-stage">
        <ThumbViewer part={part} />
      </div>
      <div>
        <div className="name">{part.name}</div>
        <div className="sub">{part.subtitle} · <strong style={{color: "var(--carbon)"}}>{brand}</strong></div>
      </div>
      <div className="sku">{part.sku}</div>
      <div className="stock-cell col-stock">In stock · 24h</div>
      <div className="col-fit"><Icons.Check style={{color: "var(--green)"}} /> <span style={{color: "var(--green)", fontWeight: 600, fontSize: 12}}>Fits</span></div>
      <div className="action-cell">
        <div className="price-cell">£{part.price}</div>
        {shop && (
          <button
            className="row-add"
            onClick={(e) => { e.stopPropagation(); shop.addToCart(part.id, 1); }}
            title="Add to cart"
          >
            {inCart ? <Icons.Check /> : <Icons.Plus />}
          </button>
        )}
      </div>
    </div>
  );
}

// ============================================================
// Lightweight thumbnail viewer (unchanged)
// ============================================================
function ThumbViewer({ part }) {
  const containerRef = useRef(null);
  const [inView, setInView] = useState(false);

  // Lazy-init: only build a WebGL context when the thumbnail scrolls into view.
  // Browsers cap concurrent WebGL contexts (~16), so an unbounded page of 3D thumbs
  // causes "Context Lost" errors on the earliest ones.
  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    if (inView) return;
    if (!("IntersectionObserver" in window)) { setInView(true); return; }
    const io = new IntersectionObserver((entries) => {
      if (entries.some(e => e.isIntersecting)) {
        setInView(true);
        io.disconnect();
      }
    }, { rootMargin: "200px" });
    io.observe(el);
    return () => io.disconnect();
  }, [inView]);

  useEffect(() => {
    const container = containerRef.current;
    if (!container || !window.THREE || !inView) return;
    const THREE = window.THREE;
    const w = Math.max(40, container.clientWidth);
    const h = Math.max(40, container.clientHeight);

    const scene = new THREE.Scene();
    scene.background = null;
    const camera = new THREE.PerspectiveCamera(30, w / h, 0.1, 100);
    camera.position.set(3.4, 2.4, 3.6);

    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setSize(w, h);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    if ("outputColorSpace" in renderer && THREE.SRGBColorSpace) renderer.outputColorSpace = THREE.SRGBColorSpace;
    else if (THREE.sRGBEncoding) renderer.outputEncoding = THREE.sRGBEncoding;
    container.appendChild(renderer.domElement);

    scene.add(new THREE.AmbientLight(0xfff8e8, 0.55));
    const key = new THREE.DirectionalLight(0xfff0d0, 1.45);
    key.position.set(4, 6, 4);
    scene.add(key);
    const fill = new THREE.DirectionalLight(0xc8d4ff, 0.55);
    fill.position.set(-4, 2, 2);
    scene.add(fill);
    const rim = new THREE.DirectionalLight(0xffffff, 0.7);
    rim.position.set(-2, 3, -5);
    scene.add(rim);

    const finish = part.finish || "metal";
    const color = new THREE.Color(part.color || "#888");
    let material;
    if (finish === "metal") material = new THREE.MeshPhysicalMaterial({ color, metalness: 0.8, roughness: 0.35 });
    else if (finish === "polished") material = new THREE.MeshPhysicalMaterial({ color, metalness: 0.95, roughness: 0.14, clearcoat: 0.6 });
    else if (finish === "satin") material = new THREE.MeshPhysicalMaterial({ color, metalness: 0.55, roughness: 0.55 });
    else if (finish === "matte") material = new THREE.MeshStandardMaterial({ color, metalness: 0.05, roughness: 0.85 });
    else if (finish === "fabric") material = new THREE.MeshStandardMaterial({ color, metalness: 0.0, roughness: 0.95 });
    else if (finish === "fluid") material = new THREE.MeshPhysicalMaterial({ color, metalness: 0.1, roughness: 0.12, transmission: 0.55, thickness: 0.4 });
    else material = new THREE.MeshStandardMaterial({ color });

    let mesh;
    const loader = new THREE.STLLoader();
    loader.load(part.model, (geometry) => {
      geometry.computeVertexNormals();
      geometry.computeBoundingBox();
      const bb = geometry.boundingBox;
      const size = new THREE.Vector3();
      bb.getSize(size);
      const center = new THREE.Vector3();
      bb.getCenter(center);
      geometry.translate(-center.x, -center.y, -center.z);
      const maxDim = Math.max(size.x, size.y, size.z);
      const scale = 1.8 / maxDim;
      geometry.scale(scale, scale, scale);
      mesh = new THREE.Mesh(geometry, material);
      scene.add(mesh);
    });

    const ro = new ResizeObserver(() => {
      const w2 = Math.max(40, container.clientWidth);
      const h2 = Math.max(40, container.clientHeight);
      renderer.setSize(w2, h2);
      camera.aspect = w2 / h2;
      camera.updateProjectionMatrix();
    });
    ro.observe(container);

    let raf;
    const tick = () => {
      if (mesh) mesh.rotation.y += 0.0035;
      renderer.render(scene, camera);
      raf = requestAnimationFrame(tick);
    };
    tick();

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
      renderer.dispose();
      if (renderer.domElement && renderer.domElement.parentNode) renderer.domElement.parentNode.removeChild(renderer.domElement);
      scene.traverse((obj) => {
        if (obj.geometry) obj.geometry.dispose();
        if (obj.material) obj.material.dispose();
      });
    };
  }, [part.id, inView]);

  return <div ref={containerRef} style={{ position: "absolute", inset: 0 }} />;
}

window.TopBar = TopBar;
window.Footer = Footer;
window.PartCard = PartCard;
window.PartRow = PartRow;
window.ThumbViewer = ThumbViewer;
