// Realistic logo-on-shirt mockup, Printify-style.
// Composes user logo into a defined "print area" on a flat-lay shirt SVG,
// integrating with fabric shading via mix-blend-mode.
// Includes background-removal (white-threshold), size + vertical position sliders.

function useProcessedLogo(srcUrl, removeBg, threshold = 235) {
  const [processed, setProcessed] = React.useState(null);
  React.useEffect(() => {
    if (!srcUrl) { setProcessed(null); return; }
    if (!removeBg) { setProcessed(srcUrl); return; }
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => {
      const c = document.createElement('canvas');
      c.width = img.naturalWidth; c.height = img.naturalHeight;
      const ctx = c.getContext('2d');
      ctx.drawImage(img, 0, 0);
      try {
        const data = ctx.getImageData(0, 0, c.width, c.height);
        const px = data.data;
        for (let i = 0; i < px.length; i += 4) {
          const r = px[i], g = px[i+1], b = px[i+2];
          // Knock out near-white pixels (with soft falloff for smoothness)
          const minV = Math.min(r, g, b);
          if (minV > threshold) {
            px[i+3] = 0;
          } else if (minV > threshold - 25) {
            px[i+3] = Math.round(px[i+3] * (threshold - minV) / 25);
          }
        }
        ctx.putImageData(data, 0, 0);
        setProcessed(c.toDataURL('image/png'));
      } catch (e) {
        // CORS / tainted canvas fallback: use original
        setProcessed(srcUrl);
      }
    };
    img.onerror = () => setProcessed(srcUrl);
    img.src = srcUrl;
  }, [srcUrl, removeBg, threshold]);
  return processed;
}

function MockupPreview() {
  const [logoSrc, setLogoSrc] = React.useState(null);
  const [removeBg, setRemoveBg] = React.useState(true);
  const [activeShirt, setActiveShirt] = React.useState(0); // photo-white default
  const [logoSize, setLogoSize] = React.useState(0.7);     // 0..1 within print area
  const [logoY, setLogoY] = React.useState(0.4);           // 0..1 within print area
  const [showPrintArea, setShowPrintArea] = React.useState(false);
  const fileInputRef = React.useRef(null);
  const dropRef = React.useRef(null);

  const processedLogo = useProcessedLogo(logoSrc, removeBg);
  const shirt = SHIRTS[activeShirt];

  const handleFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    setLogoSrc(URL.createObjectURL(file));
  };

  // Drag and drop on the mockup canvas
  React.useEffect(() => {
    const el = dropRef.current; if (!el) return;
    const onDragOver = (e) => { e.preventDefault(); el.classList.add('pm-drag-over'); };
    const onDragLeave = () => el.classList.remove('pm-drag-over');
    const onDrop = (e) => {
      e.preventDefault();
      el.classList.remove('pm-drag-over');
      const f = e.dataTransfer?.files?.[0];
      if (f) handleFile(f);
    };
    el.addEventListener('dragover', onDragOver);
    el.addEventListener('dragleave', onDragLeave);
    el.addEventListener('drop', onDrop);
    return () => {
      el.removeEventListener('dragover', onDragOver);
      el.removeEventListener('dragleave', onDragLeave);
      el.removeEventListener('drop', onDrop);
    };
  }, []);

  // Compute logo position from print area + sliders
  const pa = shirt.printArea;
  const logoBox = {
    left: `${(pa.x + (pa.w * (1 - logoSize)) / 2) * 100}%`,
    top: `${(pa.y + pa.h * logoY - (pa.h * logoSize * 0.5)) * 100}%`,
    width: `${pa.w * logoSize * 100}%`,
    height: `${pa.h * logoSize * 100}%`,
  };

  return (
    <section className="pm-section" style={{ padding: '120px 40px', background: PM.bone, color: PM.ink, position: 'relative', overflow: 'hidden' }}>
      <div className="pm-grain" style={{ opacity: .25 }} />

      <div className="pm-reveal pm-section-heading" style={{ marginBottom: 56 }}>
        <div className="pm-mono" style={{ fontSize: 11, color: PM.yellowDeep, marginBottom: 16 }}>◆ 05 / TRY IT ON</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 24, flexWrap: 'wrap' }}>
          <h2 className="pm-display pm-section-title" style={{ fontSize: 'clamp(56px,9vw,140px)', margin: 0 }}>DROP A LOGO.</h2>
          <span className="pm-script pm-section-script" style={{ fontSize: 'clamp(40px,7vw,100px)', color: PM.yellowDeep }}>
            See it printed.
          </span>
        </div>
        <p style={{ maxWidth: 560, fontSize: 15, lineHeight: 1.6, color: PM.mutedDark, marginTop: 16 }}>
          Drop or upload your logo. We&rsquo;ll mock it up on a tee so you can preview placement before committing. Real digital proof comes after you submit a quote.
        </p>
      </div>

      <div className="pm-reveal pm-mockup-grid" style={{ display: 'grid', gridTemplateColumns: '2.2fr 1fr', gap: 32, alignItems: 'flex-start' }}>
        {/* Mockup canvas */}
        <div ref={dropRef} className="pm-mockup-canvas" style={{
          position: 'relative', background: shirt.bg,
          aspectRatio: '1/1', overflow: 'hidden',
          border: `3px solid ${PM.ink}`,
          boxShadow: `12px 12px 0 ${PM.yellow}`,
          transition: 'background .4s',
        }}>
          <style>{`
            .pm-drag-over{outline:6px dashed ${PM.yellow};outline-offset:-12px}
            .pm-drag-over .pm-drop-hint{opacity:1!important;transform:translate(-50%,-50%) scale(1.05)!important}
          `}</style>

          {/* Shirt - photo or SVG */}
          <div style={{ position: 'absolute', inset: shirt.photoSrc ? 0 : '4%' }}>
            {shirt.photoSrc ? (
              <img src={shirt.photoSrc} alt={shirt.label}
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
            ) : (
              <ShirtFlatLay {...shirt} />
            )}

            {/* Print area outline (debug) */}
            {showPrintArea && (
              <div style={{
                position: 'absolute',
                left: `${pa.x * 100}%`, top: `${pa.y * 100}%`,
                width: `${pa.w * 100}%`, height: `${pa.h * 100}%`,
                border: `1.5px dashed ${shirt.dark ? PM.yellow : PM.ink}`,
                pointerEvents: 'none', opacity: .7,
              }} />
            )}

            {/* Logo on shirt - blended with fabric shading. When no logo yet,
                show a dashed preview box in the same spot so the size/position
                sliders give immediate visual feedback. */}
            {processedLogo ? (
              <div style={{
                position: 'absolute',
                ...logoBox,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                pointerEvents: 'none',
                mixBlendMode: shirt.blendMode,
                filter: 'drop-shadow(0 1px 0 rgba(0,0,0,.15))',
              }}>
                <img src={processedLogo} alt="Your logo on shirt"
                  style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
              </div>
            ) : (
              <div style={{
                position: 'absolute',
                ...logoBox,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                pointerEvents: 'none',
                border: `2px dashed ${shirt.dark ? PM.yellow : 'rgba(10,10,10,.55)'}`,
                background: 'rgba(255,255,255,.04)',
                fontFamily: FONTS.mono, fontSize: 9, letterSpacing: '.1em',
                color: shirt.dark ? PM.yellow : 'rgba(10,10,10,.7)',
                textAlign: 'center', padding: 6,
                transition: 'top .15s, left .15s, width .15s, height .15s',
              }}>
                LOGO HERE
              </div>
            )}

            {/* Subtle fabric grain overlay above the logo for extra realism */}
            <div style={{
              position: 'absolute', inset: 0, pointerEvents: 'none',
              backgroundImage: GRAIN_BG, mixBlendMode: 'overlay', opacity: .35,
            }} />
          </div>

          {/* Top bar - upload + reset */}
          <div className="pm-mockup-toolbar" style={{
            position: 'absolute', top: 16, left: 16, right: 16,
            display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap',
          }}>
            <button onClick={() => fileInputRef.current?.click()} className="pm-btn pm-btn-y"
              style={{ padding: '12px 18px', fontSize: 14, boxShadow: `4px 4px 0 ${PM.ink}` }}>
              {logoSrc ? 'Swap logo ↻' : '+ Upload logo'}
            </button>
            {logoSrc && (
              <button onClick={() => setLogoSrc(null)} className="pm-btn pm-btn-bone"
                style={{ padding: '12px 18px', fontSize: 14, boxShadow: `4px 4px 0 ${PM.ink}` }}>
                Clear ×
              </button>
            )}
          </div>

          {/* Bottom-left label */}
          <div className="pm-mockup-label" style={{
            position: 'absolute', bottom: 16, left: 20,
            fontFamily: FONTS.display, fontSize: 22,
            color: shirt.dark ? PM.bone : PM.ink, textTransform: 'uppercase', letterSpacing: '.04em',
          }}>
            {shirt.label}
          </div>

          {/* Bottom-right stamp - sits flush in the corner to fully cover the
              AI watermark on the photo. No rotation so all four corners are
              filled; small enough to feel like a brand mark, not a billboard. */}
          <div className="pm-mockup-stamp" style={{
            position: 'absolute', bottom: 0, right: 0,
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '10px 14px',
            background: PM.ink, color: PM.bone,
            boxShadow: `-3px -3px 0 ${PM.yellow}`,
            borderTop: `2px solid ${PM.yellow}`,
            borderLeft: `2px solid ${PM.yellow}`,
            pointerEvents: 'none',
            zIndex: 6,
            minWidth: 160,
          }}>
            <PMMonogram size={26} />
            <div style={{ lineHeight: 1 }}>
              <div className="pm-mono" style={{ fontSize: 8, opacity: .8, color: PM.yellow }}>STUDIO PRESS</div>
              <div className="pm-display" style={{ fontSize: 14, marginTop: 3 }}>PRESSING MATTERS</div>
            </div>
          </div>
        </div>

        {/* Right rail - controls */}
        <div className="pm-mockup-controls" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

          {/* Garment picker */}
          <div>
            <div className="pm-mono" style={{ fontSize: 11, color: PM.muted, marginBottom: 12 }}>
              ◆ GARMENT
            </div>
            <div className="pm-garment-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {SHIRTS.map((s, i) => (
                <button key={s.id} onClick={() => setActiveShirt(i)}
                  className={'pm-tee-thumb' + (activeShirt === i ? ' active' : '')}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: 10,
                    background: s.bg, color: s.dark ? PM.bone : PM.ink,
                    fontFamily: FONTS.display, fontSize: 13, textAlign: 'left', cursor: 'pointer',
                    border: '3px solid ' + (activeShirt === i ? PM.yellow : 'transparent'),
                  }}>
                  <div style={{
                    width: 28, height: 28, background: s.swatch,
                    border: `2px solid ${s.dark ? PM.bone : PM.ink}`, flexShrink: 0,
                  }} />
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {s.label}
                  </span>
                </button>
              ))}
            </div>
          </div>

          {/* Logo controls */}
          <div>
            <div className="pm-mono" style={{ fontSize: 11, color: PM.muted, marginBottom: 12 }}>
              ◆ LOGO
            </div>

            <label style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: 12,
              background: removeBg ? PM.ink : 'transparent', color: removeBg ? PM.bone : PM.ink,
              border: `2px solid ${PM.ink}`, cursor: 'pointer', fontSize: 13, fontFamily: FONTS.body,
            }}>
              <input type="checkbox" checked={removeBg} onChange={(e) => setRemoveBg(e.target.checked)}
                style={{ accentColor: PM.yellow }} />
              <span style={{ fontWeight: 500 }}>Remove white background</span>
            </label>

            <div style={{ marginTop: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: FONTS.mono, fontSize: 10, color: PM.muted, marginBottom: 6 }}>
                <span>SIZE</span><span>{Math.round(logoSize * 100)}%</span>
              </div>
              <input type="range" min={0.2} max={1} step={0.02} value={logoSize}
                onChange={(e) => setLogoSize(parseFloat(e.target.value))}
                style={{ width: '100%', accentColor: PM.yellow }} />
            </div>

            <div style={{ marginTop: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: FONTS.mono, fontSize: 10, color: PM.muted, marginBottom: 6 }}>
                <span>VERTICAL POSITION</span><span>{Math.round(logoY * 100)}%</span>
              </div>
              <input type="range" min={0.05} max={0.95} step={0.02} value={logoY}
                onChange={(e) => setLogoY(parseFloat(e.target.value))}
                style={{ width: '100%', accentColor: PM.yellow }} />
            </div>

            <button onClick={() => setShowPrintArea(!showPrintArea)}
              style={{
                marginTop: 16, padding: '8px 12px', background: 'transparent',
                border: `1.5px solid ${PM.ink}`, color: PM.ink,
                fontFamily: FONTS.mono, fontSize: 10, letterSpacing: '.1em',
                cursor: 'pointer', textTransform: 'uppercase',
              }}>
              {showPrintArea ? '◉ Hide' : '◯ Show'} print area
            </button>
          </div>

          <div style={{ padding: 16, background: PM.ink, color: PM.bone, fontFamily: FONTS.mono, fontSize: 11, lineHeight: 1.6 }}>
            ◆ FYI. The logo blends with the fabric&rsquo;s shading and folds, so dark shirts soak up the print and light shirts let it sit on top. Real production proof follows once you submit a quote.
          </div>
        </div>
      </div>

      <input type="file" ref={fileInputRef} accept="image/*" style={{ display: 'none' }}
        onChange={(e) => handleFile(e.target.files?.[0])} />
    </section>
  );
}

window.MockupPreview = MockupPreview;
