/* Cold PDP mockup — the cold STATE of ProductDetailScreen for a car-less visitor
   (from an OEM Google search, cold search, or the cold category grid). Reuses the
   real Pdp* sub-components; only two things change cold:
     1. the car bar → a "select your car" prompt (no confirmed car), and
     2. the VIN/fitment block (PdpFitGuarantee) → a fitment CHECKER.
   Per the PM's calls: content stays fully open, add-to-cart works with NO gate and
   NO nudge, and companions/alternatives show. Sandbox only, reachable at
   /p/{key}?cold=1; ports into an isCold branch inside ProductDetailScreen later.

   Own file per the new-flows convention; shares index.html's global scope. */

// Brands Speero can source / quote for (the اطلب عرض سعر flow). Prototype demo
// list; production reads this from the real brand-support config.
const PQ_BRANDS = ["تويوتا", "هوندا"];

// Circle-exclamation "!" (mirrors IconInfo's style) for the not-found modules.
function IconAlert() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9.5" />
      <path d="M12 7v6" />
      <circle cx="12" cy="16.5" r="1.2" fill="currentColor" stroke="none" />
    </svg>
  );
}

function ColdPdp({ productKey = "pads", brand, model, noData, universal, cart, onCart, onSearch, onMenu, onAddToCart, cartCount = 0, onSelectCar }) {
  const raw = findProduct(productKey);
  const p = raw ? enrichProduct(raw) : null;
  const [selOpen, setSelOpen] = React.useState(false);

  if (!p) {
    return (
      <div className="pdp-empty">
        <p>القطعة غير موجودة</p>
        <button className="pdp-link" onClick={() => window.history.back()}>عودة</button>
      </div>
    );
  }

  const cartQty = (cart && (cart.find((it) => it.key === p.key && !it.pending) || {}).qty) || 0;
  const pdpCategory = DISCOVER_CATEGORIES.find((c) => c.kinds.includes(p.kind));

  // alts / related — same derivation as the warm PDP.
  const alts = [];
  if (p.altKey && PRODUCTS[p.altKey]) alts.push({ key: p.altKey, ...PRODUCTS[p.altKey] });
  if (p.oemKey && PRODUCTS[p.oemKey]) alts.push({ key: p.oemKey, ...PRODUCTS[p.oemKey] });
  if (p.make !== "alt") {
    alts.push({ key: p.key + "_alt2", kind: p.kind, title: p.title, make: "alt", origin: "صيني", price: fmtPrice(Math.round(priceNum(p.price) * 0.62)) });
  }
  const skip = new Set([p.key, p.altKey, p.oemKey].filter(Boolean));
  const related = Object.keys(PRODUCTS)
    .filter((k) => !skip.has(k) && PRODUCTS[k].cat === "part")
    .slice(0, 4)
    .map((k) => ({ key: k, ...PRODUCTS[k] }));

  const onPickAlt = (k) => navigate("/p/" + k);
  const onAdd = () => { if (onAddToCart) onAddToCart(p.key); };
  const noop = () => {};

  return (
    <div className="pdp cl-pdp">
      {/* Cold header — no car to show, so it's the standard app chrome
          (menu + Speero + cart) rather than the PDP's car bar. */}
      <div className="pdp-stick">
        <Header onMenu={onMenu} onHome={() => navigate("/car")} onCart={onCart} cartCount={cartCount} sticky={false} />
        <button className="dsc-search pdp-search" onClick={() => onSearch && onSearch("")}>
          <IconSearch />
          <span className="dsc-search-text is-placeholder">ابحث باسم القطعة أو رقمها</span>
        </button>
      </div>

      {universal ? (
        /* Universal / non-fitment part (mats, accessories, service): fitment is
           irrelevant, so no select-car banner — just a "fits all cars" note. */
        <div className="cl-pdp-universal">
          <span className="cl-pdp-universal-icon"><IconCheck /></span>
          <span className="cl-pdp-universal-txt">قطعة عامة — تناسب جميع السيارات</span>
        </div>
      ) : noData ? (
        /* Case 3 — no fitment data at all (found by OEM). The car check is moot,
           so verification is on the part number, not the car; buy stays enabled. */
        <div className="cl-pdp-nodata">
          <span className="cl-pdp-nodata-icon"><IconAlert /></span>
          <div className="cl-pdp-nodata-body">
            <div className="cl-pdp-nodata-title">التوافق عبر رقم القطعة{p.oem ? <> <b className="mono cl-pdp-nodata-oem">{p.oem}</b></> : ""}</div>
            <div className="cl-pdp-nodata-sub">لا تتوفّر لدينا بيانات توافق لهذه القطعة. تأكّد من مطابقة رقم القطعة مع سيارتك قبل الطلب.</div>
          </div>
        </div>
      ) : (
        /* Select-your-car — a banner below the search that EXPANDS in place to
           reveal the selector (one element, not a separate card popping in). */
        <div className={"cl-pdp-select" + (selOpen ? " is-open" : "")}>
          <button className="cl-pdp-select-head" onClick={() => setSelOpen((v) => !v)} aria-expanded={selOpen}>
            <span className="cl-pdp-select-icon"><IconCarSide /></span>
            <span className="cl-pdp-select-txt">
              <span className="cl-pdp-select-title">اختر سيارتك</span>
              <span className="cl-pdp-select-sub">لعرض توافق القطعة مع سيارتك</span>
            </span>
            <span className="cl-pdp-select-chev"><IconChevron /></span>
          </button>
          <div className="cl-pdp-select-body">
            <div className="cl-pdp-select-inner">
              <SelectorCard seedMake={brand || undefined} seedModel={model || undefined} hideSaved dest={"/p/" + productKey} ctaLabel="اعرض التوافق" onAddCar={onSelectCar} />
            </div>
          </div>
        </div>
      )}

      {/* 1. Title */}
      <div className="pdp-pad pdp-pad-top">
        <nav className="pdp-crumb" aria-label="breadcrumb">
          <a className="pdp-crumb-link" onClick={() => navigate("/")}>الرئيسية</a>
          <span className="pdp-crumb-sep">/</span>
          <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/all")}>أقسام القطع</a>
          {pdpCategory && (
            <React.Fragment>
              <span className="pdp-crumb-sep">/</span>
              <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/" + pdpCategory.id + "?cold=1")}>{pdpCategory.label}</a>
            </React.Fragment>
          )}
        </nav>
        {/* No-fitment parts have no name, so the part number IS the title; drop
            the separate OEM badge (it would just repeat the title). */}
        <PdpHeader p={noData ? { ...p, title: p.oem || p.title, oem: undefined } : p} onShowMakeInfo={noop} />
      </div>

      {/* 2. Gallery */}
      <PdpGallery p={p} onShowPhotoInfo={noop} />

      {/* 3. Price */}
      <div className="pdp-pad"><PdpPrice p={p} /></div>

      {/* 4. Trust */}
      <PdpTrustStrip />

      {/* 5. Add to cart — works normally cold (no gate, no nudge). */}
      <div className="pdp-pad"><PdpCta qty={cartQty} inStock={p.inStock} reminderSet={false} onAdd={onAdd} onRemind={noop} onCart={onCart} /></div>

      {/* 6. Details (companions shown cold, per the PM's call) */}
      <PdpDetails p={p} cart={cart} onAddToCart={onAddToCart} />

      <PdpFAQ kind={p.kind} />
      <PdpAlternatives alts={alts} onPick={onPickAlt} />
      <PdpReviews rating={p.rating} reviewCount={p.reviewCount} reviews={p.reviews} />
      <PdpRelated items={related} onPick={onPickAlt} />
    </div>
  );
}

/* No-confirmed-fit state — the car is SELECTED (warm) but we have no part that's
   confirmed to fit it. We don't fake a fit and we don't dead-end: honest message
   + request-to-source (اطلبها) + notify + browse other categories for the car.
   Copy stays in the "couldn't CONFIRM a fit" register (we can't guarantee 100%).
   Demo state at /p/{key}?cold=1&nofit=1. */
function ColdPdpNoFit({ productKey = "pads", brand, cart, onCart, onSearch, onMenu, cartCount = 0 }) {
  const raw = findProduct(productKey);
  const p = raw ? enrichProduct(raw) : null;
  // PQ flow isn't built yet — the quote CTA just flashes a "قيد الإنشاء" toast
  // (reuses the global .menu-toast style used for other not-yet-built entries).
  const [toast, setToast] = React.useState(false);
  const toastTimer = React.useRef(null);
  const showToast = () => {
    setToast(true);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(false), 1600);
  };
  React.useEffect(() => () => clearTimeout(toastTimer.current), []);
  // Demo: `brand` (from the URL) simulates the selected car's brand; without it
  // we fall back to the anchored CURRENT_CAR (Toyota). supportsPQ gates the
  // quote flow: Toyota/Honda can be sourced (case 1), others can't (case 2).
  const carBrand = brand || ((typeof CURRENT_CAR !== "undefined" && CURRENT_CAR.name) ? CURRENT_CAR.name.split(" ")[0] : "");
  const supportsPQ = PQ_BRANDS.includes(carBrand);
  const sampleModel = (typeof MODELS !== "undefined" && MODELS[carBrand] && MODELS[carBrand][0]) || "";
  const carLabel = brand
    ? [brand, sampleModel, "2022"].filter(Boolean).join(" ")
    : ((typeof CURRENT_CAR !== "undefined" && (CURRENT_CAR.short || CURRENT_CAR.name)) || "سيارتك");
  const carImg = (brand && typeof resolveCarImage === "function") ? resolveCarImage(carLabel) : (typeof CURRENT_CAR !== "undefined" ? CURRENT_CAR.image : "");
  const partName = p ? p.title : "هذه القطعة";
  const pdpCategory = p && DISCOVER_CATEGORIES.find((c) => c.kinds.includes(p.kind));
  const cats = (typeof CL_CATEGORIES !== "undefined" ? CL_CATEGORIES : []).filter((c) => !pdpCategory || c.id !== pdpCategory.id).slice(0, 6);

  return (
    <div className="pdp cl-pdp">
      {/* Warm car bar — the car IS selected now. */}
      <div className="pdp-stick">
        <div className="car-bar car-bar-collapsed">
          <button className="car-bar-back" onClick={() => window.history.back()} aria-label="رجوع"><IconChevron /></button>
          <button className="car-bar-info" onClick={onMenu} aria-label="القائمة">
            <img className="car-bar-photo" src={carImg} alt={carLabel} />
            <div className="car-bar-body"><div className="car-bar-name">{carLabel}</div></div>
          </button>
          <button className="car-bar-cart" onClick={onCart} aria-label="السلة">
            <IconCart />{cartCount > 0 && <span className="car-bar-cart-badge">{cartCount}</span>}
          </button>
        </div>
        <button className="dsc-search pdp-search" onClick={() => onSearch && onSearch("")}>
          <IconSearch />
          <span className="dsc-search-text is-placeholder">ابحث باسم القطعة أو رقمها</span>
        </button>
      </div>

      <div className="pdp-pad pdp-pad-top">
        <nav className="pdp-crumb" aria-label="breadcrumb">
          <a className="pdp-crumb-link" onClick={() => navigate("/")}>الرئيسية</a>
          <span className="pdp-crumb-sep">/</span>
          <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/all")}>أقسام القطع</a>
          {pdpCategory && (
            <React.Fragment>
              <span className="pdp-crumb-sep">/</span>
              <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/" + pdpCategory.id)}>{pdpCategory.label}</a>
            </React.Fragment>
          )}
        </nav>
      </div>

      {/* The part they wanted — a compact, muted context strip (not a buy block). */}
      {p && (
        <div className="pdp-pad">
          <div className="cl-nofit-part">
            <div className="cl-nofit-part-img"><ProductImage kind={p.kind} /></div>
            <div className="cl-nofit-part-body">
              <div className="cl-nofit-part-title">{p.title}</div>
              {p.oem && <div className="prod-oem mono">{p.oem}</div>}
            </div>
          </div>
        </div>
      )}

      {/* Unavailable module — honest; the quote CTA only shows for PQ brands. */}
      <div className="pdp-pad">
        {supportsPQ ? (
          /* Case 1 — brand supports the quote flow: offer to source it. */
          <div className="cl-nofit">
            <span className="cl-nofit-icon"><IconAlert /></span>
            <h2 className="cl-nofit-title">نأسف، لم نجد {partName} مؤكّدة التوافق مع {carLabel}</h2>
            <p className="cl-nofit-sub">نبحث لك عنها من مصادرنا الموثوقة ونؤكّد التوافق قبل الشحن. اطلبها ونعود إليك بالتفاصيل والسعر.</p>
            <button className="cl-nofit-cta" onClick={showToast}>اطلب عرض سعر<IconChevron /></button>
          </div>
        ) : (
          /* Case 2 — brand not supported for quotes: honest, no CTA, browse below. */
          <div className="cl-nofit">
            <span className="cl-nofit-icon"><IconAlert /></span>
            <h2 className="cl-nofit-title">نأسف، لا تتوفّر {partName} لسيارتك حالياً</h2>
            <p className="cl-nofit-sub">لم نجد هذه القطعة متوافقة مع {carLabel}. تصفّح أقسام أخرى لسيارتك، فقد تجد ما يناسبها.</p>
          </div>
        )}
      </div>

      {/* Browse other categories for the (now known) car. */}
      <section className="a-section cl-nofit-cats">
        <div className="section-head"><h2 className="section-title">تصفّح أقسام أخرى لـ{carLabel}</h2></div>
        <div className="cd-cats">
          {cats.map((c, i) => (
            <button key={i} className="cat-card" onClick={() => navigate("/spare-parts/" + c.id)}>
              <span className="cat-icon">{c.icon}</span>
              <span className="cat-label">{c.label}</span>
            </button>
          ))}
        </div>
      </section>

      {/* PQ flow not built yet — "قيد الإنشاء" toast on the quote CTA. */}
      <div className={"menu-toast" + (toast ? " show" : "")} role="status" aria-live="polite">
        <span>قيد الإنشاء</span>
      </div>
    </div>
  );
}

/* Mismatch state — the car is selected and THIS part doesn't fit, but a
   compatible alternative exists. The best outcome: don't dead-end, surface the
   part that DOES fit and let them switch to it. Demo at /p/{key}?cold=1&mismatch=1. */
function ColdPdpMismatch({ productKey = "pads", brand, cart, onCart, onSearch, onMenu, cartCount = 0 }) {
  const raw = findProduct(productKey);
  const p = raw ? enrichProduct(raw) : null;
  const carBrand = brand || ((typeof CURRENT_CAR !== "undefined" && CURRENT_CAR.name) ? CURRENT_CAR.name.split(" ")[0] : "");
  const sampleModel = (typeof MODELS !== "undefined" && MODELS[carBrand] && MODELS[carBrand][0]) || "";
  const carLabel = brand
    ? [brand, sampleModel, "2022"].filter(Boolean).join(" ")
    : ((typeof CURRENT_CAR !== "undefined" && (CURRENT_CAR.short || CURRENT_CAR.name)) || "سيارتك");
  const carImg = (brand && typeof resolveCarImage === "function") ? resolveCarImage(carLabel) : (typeof CURRENT_CAR !== "undefined" ? CURRENT_CAR.image : "");
  const pdpCategory = p && DISCOVER_CATEGORIES.find((c) => c.kinds.includes(p.kind));

  // The fitting alternative — a real product presented as the correct-fit part.
  // Prefer the same kind (a believable "the pads that DO fit") over any part.
  const isPart = (k) => (!p || k !== p.key) && PRODUCTS[k].cat === "part";
  const altKey = Object.keys(PRODUCTS).find((k) => isPart(k) && p && PRODUCTS[k].kind === p.kind)
    || Object.keys(PRODUCTS).find(isPart);
  const fittingAlt = altKey ? enrichProduct({ key: altKey, ...PRODUCTS[altKey] }) : null;

  return (
    <div className="pdp cl-pdp">
      <div className="pdp-stick">
        <div className="car-bar car-bar-collapsed">
          <button className="car-bar-back" onClick={() => window.history.back()} aria-label="رجوع"><IconChevron /></button>
          <button className="car-bar-info" onClick={onMenu} aria-label="القائمة">
            <img className="car-bar-photo" src={carImg} alt={carLabel} />
            <div className="car-bar-body"><div className="car-bar-name">{carLabel}</div></div>
          </button>
          <button className="car-bar-cart" onClick={onCart} aria-label="السلة">
            <IconCart />{cartCount > 0 && <span className="car-bar-cart-badge">{cartCount}</span>}
          </button>
        </div>
        <button className="dsc-search pdp-search" onClick={() => onSearch && onSearch("")}>
          <IconSearch />
          <span className="dsc-search-text is-placeholder">ابحث باسم القطعة أو رقمها</span>
        </button>
      </div>

      <div className="pdp-pad pdp-pad-top">
        <nav className="pdp-crumb" aria-label="breadcrumb">
          <a className="pdp-crumb-link" onClick={() => navigate("/")}>الرئيسية</a>
          <span className="pdp-crumb-sep">/</span>
          <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/all")}>أقسام القطع</a>
          {pdpCategory && (
            <React.Fragment>
              <span className="pdp-crumb-sep">/</span>
              <a className="pdp-crumb-link" onClick={() => navigate("/spare-parts/" + pdpCategory.id)}>{pdpCategory.label}</a>
            </React.Fragment>
          )}
        </nav>
      </div>

      {/* Mismatch message (references the part that doesn't fit) → the alternative. */}
      <div className="pdp-pad">
        <div className="cl-nofit">
          <span className="cl-nofit-icon"><IconAlert /></span>
          <h2 className="cl-nofit-title">هذه القطعة لا تناسب {carLabel}</h2>
          {p && <p className="cl-nofit-ref">{p.title}{p.oem ? <> · <span className="mono">{p.oem}</span></> : ""}</p>}
        </div>
      </div>
      {fittingAlt && (
        <div className="pdp-pad cl-mismatch-alt">
          <div className="cl-mismatch-alt-head">القطعة المناسبة لسيارتك</div>
          <ProductCard p={fittingAlt} onClick={() => navigate("/p/" + fittingAlt.key)} />
        </div>
      )}
    </div>
  );
}

// Exposed for index.html's /p/{key}?cold=1 dispatch (loads after the main script).
window.CL = Object.assign(window.CL || {}, { Pdp: ColdPdp, PdpNoFit: ColdPdpNoFit, PdpMismatch: ColdPdpMismatch });
window.dispatchEvent(new Event("hashchange"));
