// ProductImage — product tile. Three layers, in priority order:
//   1. Real photo from `product.image` (cropped Spreadshirt shot) if the file
//      is on disk. If <img> errors, falls through to (2).
//   2. SVG garment silhouette in `product.kind` (tee / ls-tee / hoodie / hat /
//      jogger / tote / mug / sticker), filled with `product.swatch`, with the
//      print on the chest based on `product.mark`. Reads as an actual product
//      shape, not a colored rectangle.
//   3. Bare mark on a colored ground (legacy fallback for entries missing kind).
function ProductImage({ product, size = 'md' }) {
  const heightMap = { sm: 160, md: 320, lg: 520 };
  const h = heightMap[size] || 320;
  const [imgFailed, setImgFailed] = React.useState(false);

  // (1) Real photo path
  if (product.image && !imgFailed) {
    return (
      <div style={{
        background: '#FFFFFF', height: h, width: '100%',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        <img src={product.image} alt={product.name}
          onError={() => setImgFailed(true)}
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', display: 'block' }} />
      </div>
    );
  }

  // Shared swatch logic for SVG + legacy fallback.
  const bg = product.swatch === '#FFFFFF' ? '#F5F1E8' : product.swatch;
  const isBlackBg = product.swatch === '#0A0A0A';
  const swatchLum = (() => {
    const m = /^#([0-9a-fA-F]{6})$/.exec(bg);
    if (!m) return 1;
    const r = parseInt(m[1].slice(0, 2), 16) / 255;
    const g = parseInt(m[1].slice(2, 4), 16) / 255;
    const b = parseInt(m[1].slice(4, 6), 16) / 255;
    return 0.299 * r + 0.587 * g + 0.114 * b;
  })();
  const ink = swatchLum < 0.5 ? '#F2ECDD' : '#0E0D0A';
  const invertForDark = swatchLum < 0.5 ? 'invert(1)' : 'none';
  const sizeMul = { sm: 0.6, md: 1, lg: 1.5 }[size] || 1;

  // (2) SVG garment silhouette
  if (product.kind) {
    return (
      <div style={{
        background: '#FFFFFF', height: h, width: '100%',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        <GarmentTile
          product={product} h={h} swatch={bg} ink={ink}
          invertForDark={invertForDark} sizeMul={sizeMul}
        />
      </div>
    );
  }

  // (3) Legacy fallback — bare mark on colored ground
  return <LegacyMarkTile product={product} h={h} bg={bg} ink={ink}
    isBlackBg={isBlackBg} sizeMul={sizeMul} invertForDark={invertForDark} />;
}

// --------------------------------------------------------------------------
// Garment silhouettes — one component per kind. Each returns an inline SVG
// (filled with swatch) plus a positioned print overlay (logo image OR text).
// --------------------------------------------------------------------------
function GarmentTile({ product, h, swatch, ink, invertForDark, sizeMul }) {
  const stroke = 'rgba(20,20,20,0.18)';
  const sw = 1.3;
  const shadow = 'drop-shadow(0 8px 16px rgba(0,0,0,0.10)) drop-shadow(0 2px 4px rgba(0,0,0,0.06))';
  const kind = product.kind;

  // ---- Print element (positioned absolutely inside the wrapper)
  const print = <Print product={product} ink={ink} invertForDark={invertForDark} kind={kind} />;

  if (kind === 'sticker') {
    return (
      <img src="../../assets/logo-sticker.png" alt={product.name}
        style={{ maxWidth: '70%', maxHeight: '85%', transform: 'rotate(-4deg)', filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.30))' }} />
    );
  }

  // Wrapper that holds SVG + absolute print overlay.
  const wrap = (svg, printPos) => (
    <div style={{ position: 'relative', width: '78%', height: '88%',
      display: 'flex', alignItems: 'center', justifyContent: 'center', filter: shadow }}>
      {svg}
      <div style={{ position: 'absolute', pointerEvents: 'none', ...printPos }}>
        {print}
      </div>
    </div>
  );

  if (kind === 'tee' || kind === 'ls-tee') {
    const ls = kind === 'ls-tee';
    // Crew-neck tee silhouette. Long sleeve extends sleeve cuff downward.
    const d = ls
      ? 'M 25 38 L 70 38 Q 75 22 100 22 Q 125 22 130 38 L 175 38 L 195 95 L 188 195 L 152 205 L 152 215 Q 152 220 148 220 L 52 220 Q 48 220 48 215 L 48 205 L 12 195 L 5 95 Z'
      : 'M 25 38 L 70 38 Q 75 22 100 22 Q 125 22 130 38 L 175 38 L 195 95 L 152 108 L 152 215 Q 152 220 148 220 L 52 220 Q 48 220 48 215 L 48 108 L 5 95 Z';
    const svg = (
      <svg viewBox="0 0 200 230" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        <path d={d} fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* subtle collar ribbing */}
        <path d="M 78 38 Q 100 50 122 38" fill="none" stroke="rgba(0,0,0,0.18)" strokeWidth="1" />
      </svg>
    );
    return wrap(svg, printPos(kind, product.mark));
  }

  if (kind === 'hoodie') {
    const d = 'M 20 65 L 60 55 Q 50 38 65 22 Q 100 8 135 22 Q 150 38 140 55 L 180 65 L 198 138 L 152 145 L 152 218 Q 152 222 148 222 L 52 222 Q 48 222 48 218 L 48 145 L 2 138 Z';
    const svg = (
      <svg viewBox="0 0 200 230" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        <path d={d} fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* kangaroo pocket */}
        <path d="M 60 162 L 140 162 Q 145 162 144 167 L 132 200 Q 130 204 126 204 L 74 204 Q 70 204 68 200 L 56 167 Q 55 162 60 162 Z"
          fill="rgba(0,0,0,0.05)" stroke="rgba(0,0,0,0.18)" strokeWidth="1" />
        {/* drawstrings */}
        <line x1="86" y1="58" x2="82" y2="92" stroke="rgba(0,0,0,0.38)" strokeWidth="2" strokeLinecap="round" />
        <line x1="114" y1="58" x2="118" y2="92" stroke="rgba(0,0,0,0.38)" strokeWidth="2" strokeLinecap="round" />
        {/* hood opening */}
        <path d="M 64 56 Q 100 50 136 56" fill="none" stroke="rgba(0,0,0,0.22)" strokeWidth="1.2" />
      </svg>
    );
    return wrap(svg, printPos(kind, product.mark));
  }

  if (kind === 'hat') {
    // Dad hat front view: rounded crown + curved brim
    const svg = (
      <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        {/* brim (curves down) */}
        <path d="M 18 100 Q 100 132 182 100 Q 180 108 100 122 Q 20 108 18 100 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* crown */}
        <path d="M 30 100 Q 30 60 50 40 Q 75 18 100 18 Q 125 18 150 40 Q 170 60 170 100 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* sweatband seam */}
        <path d="M 32 96 Q 100 104 168 96" fill="none" stroke="rgba(0,0,0,0.22)" strokeWidth="1" />
      </svg>
    );
    return wrap(svg, printPos('hat', product.mark));
  }

  if (kind === 'jogger') {
    const svg = (
      <svg viewBox="0 0 200 240" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        {/* waistband */}
        <path d="M 28 22 L 172 22 L 172 52 L 28 52 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* left leg */}
        <path d="M 28 52 L 96 52 L 88 220 Q 88 228 80 228 L 56 228 Q 48 228 48 220 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* right leg */}
        <path d="M 104 52 L 172 52 L 152 220 Q 152 228 144 228 L 120 228 Q 112 228 112 220 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* drawstrings */}
        <line x1="92" y1="32" x2="86" y2="50" stroke="rgba(0,0,0,0.35)" strokeWidth="2" strokeLinecap="round" />
        <line x1="108" y1="32" x2="114" y2="50" stroke="rgba(0,0,0,0.35)" strokeWidth="2" strokeLinecap="round" />
        {/* leg seams */}
        <line x1="68" y1="58" x2="64" y2="216" stroke="rgba(0,0,0,0.12)" strokeWidth="1" />
        <line x1="132" y1="58" x2="136" y2="216" stroke="rgba(0,0,0,0.12)" strokeWidth="1" />
      </svg>
    );
    return wrap(svg, printPos('jogger', product.mark));
  }

  if (kind === 'tote') {
    const svg = (
      <svg viewBox="0 0 200 220" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        {/* handles */}
        <path d="M 55 80 Q 55 22 82 22 Q 108 22 108 80" fill="none"
          stroke={swatch} strokeWidth="6" strokeLinecap="round" />
        <path d="M 92 80 Q 92 22 118 22 Q 145 22 145 80" fill="none"
          stroke={swatch} strokeWidth="6" strokeLinecap="round" />
        {/* bag body */}
        <path d="M 30 78 L 170 78 L 162 208 Q 162 212 158 212 L 42 212 Q 38 212 38 208 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* top hem line */}
        <line x1="33" y1="86" x2="167" y2="86" stroke="rgba(0,0,0,0.18)" strokeWidth="1" />
      </svg>
    );
    return wrap(svg, printPos('tote', product.mark));
  }

  if (kind === 'mug') {
    const svg = (
      <svg viewBox="0 0 220 180" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%' }}>
        {/* handle */}
        <path d="M 140 56 Q 195 56 195 100 Q 195 144 140 144" fill="none"
          stroke={swatch} strokeWidth="14" strokeLinecap="round" />
        <path d="M 140 70 Q 178 70 178 100 Q 178 130 140 130" fill="none"
          stroke="#FFFFFF" strokeWidth="6" strokeLinecap="round" />
        {/* body */}
        <path d="M 30 40 L 142 40 Q 148 40 148 46 L 148 154 Q 148 160 142 160 L 30 160 Q 24 160 24 154 L 24 46 Q 24 40 30 40 Z"
          fill={swatch} stroke={stroke} strokeWidth={sw} strokeLinejoin="round" />
        {/* rim highlight */}
        <ellipse cx="86" cy="42" rx="58" ry="4" fill="rgba(255,255,255,0.55)" />
      </svg>
    );
    return wrap(svg, printPos('mug', product.mark));
  }

  // Unknown kind — fall back to a colored rectangle with print centered.
  return (
    <div style={{ background: swatch, width: '78%', height: '78%',
      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {print}
    </div>
  );
}

// Per-kind, per-mark position of the chest print on the silhouette wrapper.
// All numbers are percentages of the silhouette wrapper.
function printPos(kind, mark) {
  if (kind === 'tee' || kind === 'ls-tee') {
    if (mark === 'stacked')        return { top: '54%', left: '50%', transform: 'translate(-50%,-50%)', width: '38%' };
    if (mark === 'wordmark-line')  return { top: '54%', left: '50%', transform: 'translate(-50%,-50%)', width: '56%' };
    // small chest hit upper-left (wordmark = head-logo lockup)
    return                              { top: '36%', left: '36%', transform: 'translate(-50%,-50%)', width: '14%' };
  }
  if (kind === 'hoodie') {
    if (mark === 'stacked')        return { top: '42%', left: '50%', transform: 'translate(-50%,-50%)', width: '44%' };
    if (mark === 'wordmark-line')  return { top: '42%', left: '50%', transform: 'translate(-50%,-50%)', width: '56%' };
    return                              { top: '42%', left: '50%', transform: 'translate(-50%,-50%)', width: '22%' };
  }
  if (kind === 'hat')   return { top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: '48%' };
  if (kind === 'jogger')return { top: '34%', left: '34%', transform: 'translate(-50%,-50%)', width: '14%' };
  if (kind === 'tote') {
    if (mark === 'stacked') return { top: '58%', left: '50%', transform: 'translate(-50%,-50%)', width: '52%' };
    return                       { top: '58%', left: '50%', transform: 'translate(-50%,-50%)', width: '54%' };
  }
  if (kind === 'mug')   return { top: '56%', left: '40%', transform: 'translate(-50%,-50%)', width: '52%' };
  return { top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: '40%' };
}

// Render the print content (image or styled text) based on `mark`.
function Print({ product, ink, invertForDark, kind }) {
  const mark = product.mark;
  // Text marks are drawn inside an SVG so they scale to the print container,
  // never overflowing the silhouette. viewBox 100x100, preserveAspectRatio
  // meet => letters scale with whichever dimension is smaller.
  if (mark === 'stacked') {
    return (
      <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%', display: 'block', overflow: 'visible' }}>
        <text x="50" y="46" textAnchor="middle"
          fontFamily='var(--font-display, "Hanken Grotesk", "Arial Black", Impact, sans-serif)'
          fontSize="38" fontWeight="900" fill={ink}
          style={{ letterSpacing: '-1.2px', textTransform: 'uppercase' }}>BLK</text>
        <text x="50" y="86" textAnchor="middle"
          fontFamily='var(--font-display, "Hanken Grotesk", "Arial Black", Impact, sans-serif)'
          fontSize="38" fontWeight="900" fill={ink}
          style={{ letterSpacing: '-1.2px', textTransform: 'uppercase' }}>SQRL</text>
      </svg>
    );
  }
  if (mark === 'wordmark-line') {
    return (
      <svg viewBox="0 0 140 36" preserveAspectRatio="xMidYMid meet"
        style={{ width: '100%', height: '100%', display: 'block', overflow: 'visible' }}>
        <text x="70" y="29" textAnchor="middle"
          fontFamily='var(--font-display, "Hanken Grotesk", "Arial Black", Impact, sans-serif)'
          fontSize="30" fontWeight="900" fill={ink}
          style={{ letterSpacing: '-0.5px', textTransform: 'uppercase' }}>BLK SQRL®</text>
      </svg>
    );
  }
  if (mark === 'mark') {
    return <img src="../../assets/logo-mark.png" alt=""
      style={{ width: '100%', display: 'block', filter: invertForDark }} draggable="false" />;
  }
  // default = the full BLK SQRL lockup (wordmark + head)
  return <img src="../../assets/logo.png" alt=""
    style={{ width: '100%', display: 'block', filter: invertForDark }} draggable="false" />;
}

// --------------------------------------------------------------------------
// Legacy fallback: bare mark on colored ground (used only for entries that
// don't specify a `kind`, so existing demo seed data still renders sensibly).
// --------------------------------------------------------------------------
function LegacyMarkTile({ product, h, bg, ink, isBlackBg, sizeMul, invertForDark }) {
  const isWhiteTee = product.swatch === '#FFFFFF';
  let content;
  if (product.mark === 'mark') {
    content = <img src="../../assets/logo-mark.png" alt={product.name}
      style={{ maxWidth: '38%', maxHeight: '52%', filter: isBlackBg ? 'invert(1)' : 'none' }} />;
  } else if (product.mark === 'sticker') {
    content = <img src="../../assets/logo-sticker.png" alt={product.name}
      style={{ maxWidth: '55%', transform: 'rotate(-6deg)', filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.35))' }} />;
  } else if (product.mark === 'stacked') {
    content = (
      <div style={{ color: ink, fontFamily: 'var(--font-display, sans-serif)',
        fontWeight: 900, fontSize: 72 * sizeMul, lineHeight: 0.92,
        letterSpacing: '-0.02em', textAlign: 'center', textTransform: 'uppercase' }}>
        BLK<br />SQRL<span style={{ fontSize: '0.32em', verticalAlign: 'super' }}>®</span>
      </div>
    );
  } else if (product.mark === 'wordmark-line') {
    content = (
      <div style={{ color: ink, fontFamily: 'var(--font-display, sans-serif)',
        fontWeight: 900, fontSize: 52 * sizeMul, lineHeight: 1,
        letterSpacing: '-0.01em', textAlign: 'center', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
        BLK&nbsp;SQRL<span style={{ fontSize: '0.42em', verticalAlign: 'super' }}>®</span>
      </div>
    );
  } else if (product.mark === 'wordmark-inv') {
    content = <img src="../../assets/logo.png" alt={product.name}
      style={{ maxWidth: '60%', maxHeight: '68%', filter: 'invert(1)' }} />;
  } else {
    content = <img src="../../assets/logo.png" alt={product.name}
      style={{ maxWidth: '60%', maxHeight: '68%' }} />;
  }
  return (
    <div style={{ background: bg, height: h, width: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative', overflow: 'hidden',
      border: isWhiteTee ? '1px solid var(--blk)' : 'none' }}>
      {content}
    </div>
  );
}

window.ProductImage = ProductImage;
