// ============================================================================
// Sun Systems Catalogue — React Components
// ============================================================================

const { useState, useEffect, useMemo, useRef, useCallback } = React;

// ---------- Currency formatter ----------
const fmtINR = (n) => '₹' + Number(n).toLocaleString('en-IN');

// ---------- Brand-tinted SVG placeholder ----------
function PlaceholderArt({ seed = 0, label = '' }) {
  // Build a soft, abstract laptop placeholder — paper-tone gradient + subtle laptop glyph
  const hueShift = (seed * 37) % 60;
  return (
    <svg className="placeholder-art" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id={`pg-${seed}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="var(--surface-2)" />
          <stop offset="100%" stopColor="var(--bg-elev)" />
        </linearGradient>
        <pattern id={`pp-${seed}`} width="6" height="6" patternUnits="userSpaceOnUse" patternTransform={`rotate(${30 + hueShift})`}>
          <line x1="0" y1="0" x2="0" y2="6" stroke="var(--line)" strokeWidth="0.5" opacity="0.5" />
        </pattern>
      </defs>
      <rect width="400" height="300" fill={`url(#pg-${seed})`} />
      <rect width="400" height="300" fill={`url(#pp-${seed})`} />
      {/* Laptop glyph */}
      <g transform="translate(200 150)" stroke="var(--ink-4)" fill="none" strokeWidth="1.5" opacity="0.6">
        <rect x="-70" y="-44" width="140" height="88" rx="6" />
        <rect x="-60" y="-36" width="120" height="68" rx="2" fill="var(--bg)" />
        <rect x="-90" y="46" width="180" height="6" rx="3" fill="var(--surface)" />
      </g>
    </svg>
  );
}

// ---------- Icons ----------
const Icon = {
  Search: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>),
  Filter: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M3 6h18M6 12h12M10 18h4"/></svg>),
  Cpu: (p) => (<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 14h3M1 9h3M1 14h3"/></svg>),
  Memory: (p) => (<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M6 19V5h12v14"/><path d="M6 12h12M9 5v3M12 5v3M15 5v3"/></svg>),
  Hdd: (p) => (<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="7" cy="12" r="1.5"/><path d="M11 12h7"/></svg>),
  Display: (p) => (<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="2" y="4" width="20" height="14" rx="2"/><path d="M9 21h6M12 18v3"/></svg>),
  WhatsApp: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.1-.2.3-.7.9-.9 1.1-.2.1-.3.2-.6 0-.3-.1-1.2-.4-2.3-1.4-.8-.7-1.4-1.6-1.5-1.9-.1-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.1.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.9-2-.2-.5-.5-.4-.6-.4h-.5c-.2 0-.5.1-.7.4-.3.3-.9.9-.9 2.2 0 1.3.9 2.5 1.1 2.7.1.2 1.8 2.8 4.4 3.9 2.6 1.1 2.6.7 3.1.7.5 0 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4M12 22c-2 0-3.9-.5-5.6-1.5L2 22l1.5-4.4C2.5 15.9 2 14 2 12 2 6.5 6.5 2 12 2s10 4.5 10 10-4.5 10-10 10"/></svg>),
  Compare: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M3 6h7v14H3zM14 4h7v18h-7z"/></svg>),
  Eye: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7"/><circle cx="12" cy="12" r="3"/></svg>),
  X: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M18 6 6 18M6 6l12 12"/></svg>),
  Check: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}><path d="M20 6 9 17l-5-5"/></svg>),
  Phone: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92"/></svg>),
  MapPin: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M20 10c0 7-8 12-8 12s-8-5-8-12a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/></svg>),
  Upload: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>),
  Sun: (p) => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>),
  Mail: (p) => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>),
};

// ---------- WhatsApp link builder ----------
// `sel` (optional) is the chosen variant: { ram, storage, price }
function buildWaUrl(phone, product, sel) {
  let msg;
  if (product && sel) {
    msg = `Hi Sun Systems! I'd like to know more about the *${product.model}* (${product.processor}, ${sel.ram}GB / ${sel.storage}GB SSD) listed at ${fmtINR(sel.price)}. Is it available?`;
  } else if (product) {
    msg = `Hi Sun Systems! I'd like to know more about the *${product.model}* (${product.processor}). Is it available?`;
  } else {
    msg = `Hi Sun Systems! I'd like to know more about your laptops.`;
  }
  return `https://wa.me/91${phone}?text=${encodeURIComponent(msg)}`;
}

// ---------- Variant engine (base price + RAM/SSD upgrades) ----------
// Reads baseRam/baseStorage/basePrice/addRam/addSsd and produces the list of
// 1–4 configurations plus a price function. Upgrade targets are 16GB and 512GB.
function variantsOf(p) {
  const baseRam = Number(p.baseRam) || 0;
  const baseStorage = Number(p.baseStorage) || 0;
  const basePrice = Number(p.basePrice) || 0;
  const addRam = (Number(p.addRam) > 0 && baseRam < 16) ? Number(p.addRam) : 0;
  const addSsd = (Number(p.addSsd) > 0 && baseStorage < 512) ? Number(p.addSsd) : 0;
  const ramOptions = addRam ? [baseRam, 16] : [baseRam];
  const storageOptions = addSsd ? [baseStorage, 512] : [baseStorage];
  const priceFor = (ram, storage) =>
    basePrice + (ram > baseRam ? addRam : 0) + (storage > baseStorage ? addSsd : 0);
  const prices = [];
  ramOptions.forEach(r => storageOptions.forEach(s => prices.push(priceFor(r, s))));
  return {
    baseRam, baseStorage, basePrice, addRam, addSsd,
    ramOptions, storageOptions, priceFor,
    hasVariants: ramOptions.length > 1 || storageOptions.length > 1,
    priceMin: Math.min(...prices), priceMax: Math.max(...prices),
  };
}

// ---------- Variant pill selector ----------
function VariantPills({ label, options, value, unit, onChange }) {
  return (
    <div className="variant-group">
      <span className="variant-label">{label}</span>
      <div className="variant-pills">
        {options.map(o => (
          <button key={o} type="button"
            className={`variant-pill ${o === value ? 'active' : ''}`}
            onClick={(e) => { e.stopPropagation(); onChange(o); }}>
            {o}{unit}
          </button>
        ))}
      </div>
    </div>
  );
}

// ---------- Image resolver — supports `image` (single) or `images` (array) ----------
function getImages(product) {
  if (Array.isArray(product.images) && product.images.length) return product.images;
  if (product.image) return [product.image];
  return [];
}
function getCover(product) {
  const imgs = getImages(product);
  return imgs[0] || null;
}

// ---------- Card ----------
function ProductCard({ product, variant, showPrice, onOpen, onCompare, isComparing, waPhone }) {
  const v = variantsOf(product);
  const [sel, setSel] = useState({ ram: v.ramOptions[0], storage: v.storageOptions[0] });
  const price = v.priceFor(sel.ram, sel.storage);
  const ramLabel = `${sel.ram}GB`;
  const storageLabel = `${sel.storage}GB SSD`;
  const [imgError, setImgError] = useState(false);
  const cover = getCover(product);
  const showImg = cover && !imgError;
  return (
    <article
      className={`card ${product.stock === 'sold-out' ? 'sold-out' : ''} ${isComparing ? 'in-compare' : ''}`}
      data-variant={variant}
      onClick={() => onOpen(product)}
    >
      <div className="card-image">
        {showImg
          ? <img src={cover} alt={product.model} onError={() => setImgError(true)} />
          : <PlaceholderArt seed={parseInt(product.id.replace(/\D/g,'')) || 0} />}
        <div className="card-badges">
          <span className={`badge-stock ${product.stock}`}>
            <span className="dot" />
            {product.stock === 'in-stock' ? 'In stock' : 'Sold out'}
          </span>
          {product.featured && <span className="badge-featured">Featured</span>}
        </div>
        {!showImg && variant !== 'minimal' && <span className="placeholder-label">photo coming soon</span>}
      </div>
      <div className="card-body">
        {variant === 'minimal' && (
          <div className="card-badges" style={{position:'static', marginBottom:6}}>
            <span className={`badge-stock ${product.stock}`}>
              <span className="dot" />
              {product.stock === 'in-stock' ? 'In stock' : 'Sold out'}
            </span>
            {product.featured && <span className="badge-featured">Featured</span>}
          </div>
        )}
        <div className="card-brand">{product.brand} · {product.series}</div>
        <h3 className="card-title">{product.model}</h3>
        <div className="card-specs">
          <span className="card-spec-item"><Icon.Cpu />{product.cpuTier}{product.generation ? ` · ${product.generation}th gen` : ''}</span>
          {v.ramOptions.length === 1 && <span className="card-spec-item"><Icon.Memory />{ramLabel}</span>}
          {v.storageOptions.length === 1 && <span className="card-spec-item"><Icon.Hdd />{storageLabel}</span>}
          <span className="card-spec-item"><Icon.Display />{product.displayLabel}</span>
        </div>
        {v.hasVariants && (
          <div className="variant-row" onClick={(e) => e.stopPropagation()}>
            {v.ramOptions.length > 1 && (
              <VariantPills label="RAM" options={v.ramOptions} value={sel.ram} unit="GB"
                onChange={(o) => setSel(s => ({ ...s, ram: o }))} />
            )}
            {v.storageOptions.length > 1 && (
              <VariantPills label="SSD" options={v.storageOptions} value={sel.storage} unit="GB"
                onChange={(o) => setSel(s => ({ ...s, storage: o }))} />
            )}
          </div>
        )}
        <div className="card-foot">
          {showPrice ? (
            <div className="card-price">
              <span className="card-price-num">{fmtINR(price)}</span>
              <span className="card-price-label">incl. of all taxes</span>
            </div>
          ) : (
            <div className="card-price">
              <span className="card-price-num" style={{fontSize:18, color:'var(--ink-3)'}}>Ask for price</span>
            </div>
          )}
          <div className="card-actions" onClick={(e) => e.stopPropagation()}>
            <button
              className={`icon-btn compare ${isComparing ? 'active' : ''}`}
              title={isComparing ? 'Remove from compare' : 'Add to compare'}
              onClick={() => onCompare(product)}
            >
              <Icon.Compare />
            </button>
            <a
              className="icon-btn wa"
              title="Ask on WhatsApp"
              href={buildWaUrl(waPhone, product, { ram: sel.ram, storage: sel.storage, price })}
              target="_blank"
              rel="noopener"
            >
              <Icon.WhatsApp />
            </a>
          </div>
        </div>
      </div>
    </article>
  );
}

// ---------- Detail modal ----------
function ProductModal({ product, onClose, showPrice, waPhone }) {
  const images = getImages(product);
  const [imgIdx, setImgIdx] = useState(0);
  const [failed, setFailed] = useState({});
  const v = variantsOf(product);
  const [sel, setSel] = useState({ ram: v.ramOptions[0], storage: v.storageOptions[0] });
  const price = v.priceFor(sel.ram, sel.storage);
  const go = (dir) => setImgIdx(i => (i + dir + images.length) % images.length);
  // Touch swipe for mobile gallery
  const touchX = useRef(null);
  const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchX.current == null || images.length < 2) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
    touchX.current = null;
  };
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight' && images.length > 1) setImgIdx(i => (i + 1) % images.length);
      if (e.key === 'ArrowLeft' && images.length > 1) setImgIdx(i => (i - 1 + images.length) % images.length);
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose, images.length]);
  if (!product) return null;
  const priceStr = fmtINR(price);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><Icon.X /></button>
        <div className="modal-grid">
          <div className="modal-image" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
            {images[imgIdx] && !failed[images[imgIdx]]
              ? <img key={imgIdx} src={images[imgIdx]} alt={product.model} onError={() => setFailed(f => ({ ...f, [images[imgIdx]]: true }))} />
              : <PlaceholderArt seed={parseInt(product.id.replace(/\D/g,'')) || 0} />
            }
            {images.length > 1 && (
              <>
                <button className="gallery-nav prev" onClick={() => go(-1)} aria-label="Previous">‹</button>
                <button className="gallery-nav next" onClick={() => go(1)} aria-label="Next">›</button>
                <div className="gallery-dots">
                  {images.map((_, i) => (
                    <button key={i} className={`gallery-dot ${i===imgIdx?'active':''}`} onClick={() => setImgIdx(i)} />
                  ))}
                </div>
              </>
            )}
            <div className="card-badges">
              <span className={`badge-stock ${product.stock}`}>
                <span className="dot" />
                {product.stock === 'in-stock' ? 'In stock' : 'Sold out'}
              </span>
            </div>
          </div>
          <div className="modal-body">
            <div className="modal-brand">{product.brand} · {product.series}</div>
            <h2 className="modal-title">{product.model}</h2>
            {showPrice && (
              <div className="modal-price">
                {priceStr}
                <span className="modal-price-label">INR</span>
              </div>
            )}
            {v.hasVariants && (
              <div className="modal-variants">
                {v.ramOptions.length > 1 && (
                  <VariantPills label="RAM" options={v.ramOptions} value={sel.ram} unit="GB"
                    onChange={(o) => setSel(s => ({ ...s, ram: o }))} />
                )}
                {v.storageOptions.length > 1 && (
                  <VariantPills label="Storage" options={v.storageOptions} value={sel.storage} unit="GB"
                    onChange={(o) => setSel(s => ({ ...s, storage: o }))} />
                )}
              </div>
            )}
            <dl className="spec-table">
              <dt>Processor</dt><dd>{product.processor}</dd>
              {v.ramOptions.length === 1 && (<><dt>Memory</dt><dd>{sel.ram}GB</dd></>)}
              {v.storageOptions.length === 1 && (<><dt>Storage</dt><dd>{sel.storage}GB SSD</dd></>)}
              <dt>Display</dt><dd>{product.displayLabel}</dd>
              <dt>Graphics</dt><dd>{product.graphics || 'Integrated'}</dd>
              {product.notes && (<><dt>Notes</dt><dd>{product.notes}</dd></>)}
            </dl>
            <div className="modal-actions">
              <a className="btn btn-wa" href={buildWaUrl(waPhone, product, { ram: sel.ram, storage: sel.storage, price })} target="_blank" rel="noopener">
                <Icon.WhatsApp /> Ask on WhatsApp
              </a>
              <button className="btn btn-ghost" onClick={() => {
                document.getElementById('inquiry')?.scrollIntoView({behavior:'smooth', block:'start'});
                onClose();
              }}>
                Send inquiry
              </button>
            </div>
            <p style={{fontSize:12, color:'var(--ink-3)', marginTop:8}}>
              Pre-owned business laptops · Tested & cleaned · 1-month testing + 6-month service warranty
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Compare modal ----------
function CompareModal({ products, onClose, onRemove, showPrice }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);

  // Highlight best in each numeric row
  const best = useMemo(() => {
    const ramMax = Math.max(...products.map(p => p.ram));
    const stoMax = Math.max(...products.map(p => p.storage));
    const priceMin = Math.min(...products.map(p => p.priceMin));
    return { ramMax, stoMax, priceMin };
  }, [products]);

  const rows = [
    { label: 'Brand', get: p => p.brand },
    { label: 'Series', get: p => p.series },
    { label: 'Processor', get: p => p.processor },
    { label: 'Generation', get: p => p.generation ? `${p.generation}th gen` : '—' },
    { label: 'RAM', get: p => p.ramLabel, highlight: p => p.ram === best.ramMax },
    { label: 'Storage', get: p => p.storageLabel, highlight: p => p.storage === best.stoMax },
    { label: 'Display', get: p => p.displayLabel },
    { label: 'Graphics', get: p => p.graphics || 'Integrated' },
    { label: 'Stock', get: p => p.stock === 'in-stock' ? 'In stock' : 'Sold out' },
  ];
  if (showPrice) rows.push({
    label: 'Price (INR)',
    get: p => p.priceMin === p.priceMax ? fmtINR(p.priceMin) : `${fmtINR(p.priceMin)}–${fmtINR(p.priceMax)}`,
    highlight: p => p.priceMin === best.priceMin
  });

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="compare-table-wrap" onClick={(e) => e.stopPropagation()}>
        <div className="compare-table-head">
          <h2>Side-by-side</h2>
          <button className="modal-close" style={{position:'static'}} onClick={onClose}><Icon.X /></button>
        </div>
        <div style={{overflow:'auto'}}>
          <table className="compare-table">
            <thead>
              <tr>
                <th></th>
                {products.map(p => (
                  <td key={p.id} className="product-head">
                    <div className="product-head-brand">{p.brand}</div>
                    <h4 className="product-head-title">{p.model}</h4>
                    <button
                      onClick={() => onRemove(p)}
                      style={{marginTop:8, background:'transparent', border:'none', color:'var(--ink-3)', fontSize:12, cursor:'pointer', textDecoration:'underline'}}
                    >Remove</button>
                  </td>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map(row => (
                <tr key={row.label}>
                  <th>{row.label}</th>
                  {products.map(p => (
                    <td key={p.id} className={row.highlight && row.highlight(p) ? 'highlight' : ''}>
                      {row.get(p)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProductCard, ProductModal, CompareModal, Icon, fmtINR, buildWaUrl, PlaceholderArt, variantsOf, VariantPills });
