// MRB Auto storefront — Product detail page (mobile-first)
const _mkP = (n) => (props) => { const C = window.MRBAutoDesignSystem_73c751 && window.MRBAutoDesignSystem_73c751[n]; return C ? React.createElement(C, props) : null; };
const Icon = _mkP('Icon'), Button = _mkP('Button'), IconButton = _mkP('IconButton'), Badge = _mkP('Badge'),
  Rating = _mkP('Rating'), StockIndicator = _mkP('StockIndicator'), StickyAddToCart = _mkP('StickyAddToCart'),
  CrossSell = _mkP('CrossSell'), UpsellCompare = _mkP('UpsellCompare'), ReviewSummary = _mkP('ReviewSummary'),
  TrustItem = _mkP('TrustItem'), FreeShippingBar = _mkP('FreeShippingBar'), ProductCard = _mkP('ProductCard');

const euros = (n) => n.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', minimumFractionDigits: 0, maximumFractionDigits: 0 });

function Breadcrumb({ items }) {
  return (
    <nav style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', fontFamily: 'var(--font-sans)', fontSize: '13px', color: 'var(--text-muted)', padding: '14px 0' }}>
      {items.map((it, i) => (
        <React.Fragment key={it}>
          {i > 0 && <Icon name="chevronRight" size={13} color="var(--ink-300)" />}
          <a href={it === 'Accueil' ? 'index.html' : (it.indexOf('Marche') === 0 ? 'catalog.html' : '#')} style={{ color: i === items.length - 1 ? 'var(--text-primary)' : 'var(--text-muted)', fontWeight: i === items.length - 1 ? 600 : 400 }}>{it}</a>
        </React.Fragment>
      ))}
    </nav>
  );
}

function Placeholder({ h = '100%', label }) {
  return (
    <div style={{ width: '100%', height: h, background: 'var(--surface-tile)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, backgroundImage: 'repeating-linear-gradient(135deg, transparent 0 13px, rgba(14,15,18,0.02) 13px 14px)' }}>
      <Icon name="wrench" size={40} strokeWidth={1.4} color="var(--ink-300)" />
      {label && <span style={{ fontFamily: 'var(--font-mono)', fontSize: '10px', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-400)' }}>{label}</span>}
    </div>
  );
}

function Gallery() {
  const [active, setActive] = React.useState(0);
  const shots = ['Vue 3/4', 'Profil', 'Détail fixation', 'Monté sur véhicule'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ position: 'relative', aspectRatio: '4 / 3', borderRadius: 'var(--radius-card)', overflow: 'hidden', border: '1px solid var(--border-default)' }}>
        <div style={{ position: 'absolute', top: 14, left: 14, zIndex: 2, display: 'flex', gap: 6 }}>
          <Badge variant="top">Top vente</Badge>
          <Badge variant="sale">-22%</Badge>
        </div>
        <Placeholder label={shots[active]} />
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        {shots.map((s, i) => (
          <button key={s} type="button" onClick={() => setActive(i)}
            style={{ flex: 1, aspectRatio: '1 / 1', borderRadius: 'var(--radius-md)', overflow: 'hidden', border: `2px solid ${active === i ? 'var(--accent)' : 'var(--border-default)'}`, cursor: 'pointer', padding: 0, background: 'none' }}>
            <Placeholder />
          </button>
        ))}
      </div>
    </div>
  );
}

function Spec({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '11px 0', borderBottom: '1px solid var(--border-subtle)' }}>
      <span style={{ fontFamily: 'var(--font-sans)', fontSize: '13.5px', color: 'var(--text-muted)' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-sans)', fontSize: '13.5px', fontWeight: 600, color: 'var(--text-primary)', textAlign: 'right' }}>{value}</span>
    </div>
  );
}

function Info({ onAdd }) {
  const [qty, setQty] = React.useState(1);
  const [wished, setWished] = React.useState(false);
  const price = 249, oldPrice = 319;
  return (
    <div className="product-info-sticky" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', fontWeight: 700, letterSpacing: '0.02em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Mercedes GLC X253 · SKU MRB-MP-0421</span>
        <h1 style={{ margin: '8px 0 0', fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: 'var(--ls-display)', lineHeight: 0.98, fontSize: 'clamp(1.7rem, 5vw, 2.4rem)', color: 'var(--text-primary)' }}>
          Marche-pieds aluminium GLC X253 & Coupé C253
        </h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12, flexWrap: 'wrap' }}>
          <Rating value={4.9} count={214} />
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'var(--font-sans)', fontSize: '13px', fontWeight: 600, color: 'var(--status-success)' }}>
            <Icon name="checkCircle" size={15} /> Compatibilité vérifiée
          </span>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(2.4rem, 7vw, 3rem)', lineHeight: 1, color: 'var(--text-price)' }}>{euros(price)}</span>
        <span style={{ fontFamily: 'var(--font-sans)', fontSize: '16px', color: 'var(--text-price-old)', textDecoration: 'line-through' }}>{euros(oldPrice)}</span>
        <Badge variant="sale">Économisez {euros(oldPrice - price)}</Badge>
      </div>
      <span style={{ fontFamily: 'var(--font-sans)', fontSize: '13px', color: 'var(--text-muted)', marginTop: -8 }}>ou 4× 62 €/mois sans frais · TVA incluse</span>

      <StockIndicator stock={6} total={12} countdownTo={Date.now() + 8 * 3600 * 1000} />

      {/* qty + add */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-pill)', height: 56 }}>
          <button type="button" aria-label="Moins" onClick={() => setQty((q) => Math.max(1, q - 1))} style={qtyBtn}><Icon name="minus" size={16} /></button>
          <span style={{ minWidth: 34, textAlign: 'center', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '16px' }}>{qty}</span>
          <button type="button" aria-label="Plus" onClick={() => setQty((q) => q + 1)} style={qtyBtn}><Icon name="plus" size={16} /></button>
        </div>
        <Button variant="accent" size="lg" iconLeft="cart" onClick={() => onAdd(qty)} style={{ flex: 1, minWidth: 200 }}>Ajouter au panier</Button>
        <button type="button" aria-label="Favoris" onClick={() => setWished((w) => !w)}
          style={{ width: 56, height: 56, flexShrink: 0, borderRadius: 'var(--radius-pill)', border: '1px solid var(--border-strong)', background: 'var(--surface-card)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: wished ? 'var(--accent)' : 'var(--text-secondary)' }}>
          <Icon name="heart" size={22} fill={wished ? 'var(--accent)' : 'none'} />
        </button>
      </div>

      <FreeShippingBar cartTotal={price * qty} threshold={300} />

      {/* reassurance mini */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 4 }}>
        <TrustItem icon="truck" title="Expédié sous 24-48h" text="Colis renforcé, suivi inclus" />
        <TrustItem icon="wrench" title="Sans perçage" text="Fixation sur points d'origine" />
        <TrustItem icon="shieldCheck" title="Garantie 14 jours" text="Satisfait ou remboursé" />
        <TrustItem icon="message" title="Conseil montage" text="Par téléphone & WhatsApp" />
      </div>

      {/* specs */}
      <div style={{ marginTop: 8 }}>
        <h2 style={{ margin: '0 0 6px', fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: 'var(--ls-display)', fontSize: '1.2rem', color: 'var(--text-primary)' }}>Caractéristiques</h2>
        <Spec label="Matériau" value="Aluminium + revêtement antidérapant" />
        <Spec label="Compatibilité" value="GLC X253 & Coupé C253 (2015-2022)" />
        <Spec label="Finitions" value="AMG Line & standard" />
        <Spec label="Montage" value="Sur points d'origine, sans perçage" />
        <Spec label="Livré avec" value="Paire + visserie + notice FR" />
        <Spec label="Garantie" value="3 ans" />
      </div>
    </div>
  );
}

const qtyBtn = { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 48, height: 56, border: 'none', background: 'transparent', color: 'var(--text-primary)', cursor: 'pointer' };

function Product() {
  const [cart, setCart] = React.useState(2);
  const [toast, setToast] = React.useState('');
  const timer = React.useRef(null);
  const notify = (m) => { setToast(m); clearTimeout(timer.current); timer.current = setTimeout(() => setToast(''), 2200); };
  const add = (qty = 1) => { setCart((c) => c + qty); notify('Ajouté au panier'); };

  const related = (window.MRB_DATA ? window.MRB_DATA.bestSellers : []).slice(0, 4);

  return (
    <React.Fragment>
      <window.MRBHeader cartCount={cart} onSearch={() => {}} active="Mercedes" />

      <div className="kit-wrap">
        <Breadcrumb items={['Accueil', 'Mercedes', 'Marche-pieds', 'GLC X253']} />
      </div>

      <main className="kit-wrap" style={{ paddingBottom: 64 }}>
        <div className="product-layout">
          <Gallery />
          <Info onAdd={add} />
        </div>

        {/* Upsell */}
        <section style={{ marginTop: 56 }}>
          <UpsellCompare
            title="Choisissez votre finition"
            options={[
              { name: 'Alu brossé', price: 249, features: ['Fixation origine sans perçage', 'Revêtement antidérapant', 'Garantie 3 ans'] },
              { name: 'Alu + LED', price: 319, recommended: true, note: '+28%', features: ['Fixation origine sans perçage', 'Éclairage LED d\'accueil', 'Revêtement antidérapant', 'Garantie 3 ans'] },
            ]}
            onChoose={(opt) => { add(1); }} />
        </section>

        {/* Cross-sell */}
        <section style={{ marginTop: 40 }}>
          <CrossSell
            lead={{ title: 'Marche-pieds alu GLC X253', price: 249 }}
            items={[{ title: 'Kit visserie inox renforcé', price: 29 }, { title: 'Tapis sur-mesure GLC X253', price: 59 }]}
            onAddBundle={(chosen) => { add(1 + chosen.length); }} />
        </section>

        {/* Reviews */}
        <section style={{ marginTop: 56 }}>
          <h2 className="h-sec" style={{ margin: '0 0 24px', fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: 'var(--ls-display)', lineHeight: 0.95, color: 'var(--text-primary)' }}>Avis vérifiés</h2>
          <ReviewSummary average={4.9} count={214} distribution={[180, 24, 6, 2, 2]}
            reviews={[
              { rating: 5, text: 'Montage nickel en 30 min sur ma GLC 2018, sans perçage comme annoncé. Finition alu superbe, on dirait de l\'origine.', author: 'Karim T.', vehicle: 'GLC X253', date: '18/06/2026', verified: true },
              { rating: 5, text: 'Reçu en 48h, très bien emballé. Le SAV m\'a confirmé la compatibilité AMG Line avant l\'achat. Parfait.', author: 'Sophie R.', vehicle: 'GLC Coupé C253', date: '02/06/2026', verified: true },
              { rating: 4, text: 'Très bon produit, juste un peu lourd à manipuler seul au montage. Résultat au top.', author: 'David M.', vehicle: 'GLC X253', date: '21/05/2026', verified: true },
            ]} />
        </section>

        {/* Related */}
        <section style={{ marginTop: 56 }}>
          <h2 className="h-sec" style={{ margin: '0 0 24px', fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: 'var(--ls-display)', lineHeight: 0.95, color: 'var(--text-primary)' }}>Vous aimerez aussi</h2>
          <div className="prod-grid">
            {related.map((p) => <ProductCard key={p.title} {...p} onAdd={() => add(1)} />)}
          </div>
        </section>
      </main>

      {/* Mobile sticky add-to-cart */}
      <div className="only-mobile" style={{ position: 'sticky', bottom: 0, zIndex: 35 }}>
        <StickyAddToCart className="sticky-cart-m" title="Marche-pieds alu GLC X253" vehicle="Mercedes GLC X253" price={249} oldPrice={319} onAdd={({ qty }) => add(qty)} />
      </div>

      <window.MRBFooter />

      {toast && (
        <div style={{ position: 'fixed', left: '50%', bottom: 90, transform: 'translateX(-50%)', zIndex: 80, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--ink-900)', color: 'var(--white)', padding: '13px 20px', borderRadius: 'var(--radius-pill)', boxShadow: 'var(--shadow-xl)', fontFamily: 'var(--font-sans)', fontSize: '14px', fontWeight: 600 }}>
          <Icon name="checkCircle" size={18} color="var(--accent)" /> {toast}
        </div>
      )}
    </React.Fragment>
  );
}

(function mount() {
  const ns = window.MRBAutoDesignSystem_73c751;
  if (!ns || typeof ns.Icon !== 'function' || !window.MRBHeader || !window.MRBFooter) return setTimeout(mount, 30);
  const el = document.getElementById('page-root');
  if (!el || el.__mounted) return;
  el.__mounted = true;
  ReactDOM.createRoot(el).render(<Product />);
})();
