/* ============================================================
   TRYONME Landing — BeforeAfter slider, Features grid, Extension
   ============================================================ */

function BeforeAfter() {
  const [pos, setPos] = useState(50);
  const [activeFit, setActiveFit] = useState(0);
  const dragging = useRef(false);
  const wrapRef = useRef(null);

  const fits = [
    { name: "VINTAGE TEE",    color: "#FF4D8B", garment: "tee" },
    { name: "PARKA",           color: "#2D3D7A", garment: "parka" },
    { name: "MESH TANK",       color: "#FFC83D", garment: "tank" },
  ];

  const handle = (clientX) => {
    if (!wrapRef.current) return;
    const r = wrapRef.current.getBoundingClientRect();
    const p = ((clientX - r.left) / r.width) * 100;
    setPos(Math.max(2, Math.min(98, p)));
  };

  useEffect(() => {
    const move = (e) => {
      if (!dragging.current) return;
      handle(e.touches ? e.touches[0].clientX : e.clientX);
    };
    const up = () => { dragging.current = false; };
    window.addEventListener("mousemove", move);
    window.addEventListener("touchmove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchend", up);
    };
  }, []);

  return (
    <section className="section" id="demo" style={{ background: "var(--blue)", color: "var(--cream)" }}>
      <div className="container">
        <div className="section__head reveal" style={{ color: "var(--cream)" }}>
          <span className="num" style={{ color: "var(--yellow)" }}>§</span>
          <Eyebrow color="var(--yellow)">LIVE DEMO</Eyebrow>
          <hr style={{ flex: 1, border: "none", height: 2, background: "var(--cream)" }}/>
          <Eyebrow color="var(--cream)">DRAG ME →</Eyebrow>
        </div>

        <h2 className="display reveal" style={{ fontSize: "clamp(42px, 6.5vw, 96px)", maxWidth: 1100, color: "var(--cream)" }}>
          DRAG TO SEE THE
          <br/>
          <span style={{ color: "var(--yellow)" }}>BEFORE → AFTER.</span>
        </h2>
        <p className="reveal delay-1" style={{ marginTop: 18, fontSize: 18, opacity: 0.9, maxWidth: 580 }}>
          Same person, three outfits, zero changing rooms. Tap a fit to swap it.
        </p>

        <div
          className="ba reveal delay-2"
          ref={wrapRef}
          onMouseDown={(e) => { dragging.current = true; handle(e.clientX); }}
          onTouchStart={(e) => { dragging.current = true; handle(e.touches[0].clientX); }}
        >
          <div className="ba__layer ba__after">
            <BAImage variant="after" fit={fits[activeFit]} />
            <div className="ba__tag ba__tag--after chip chip--yellow">AFTER</div>
          </div>
          <div className="ba__layer ba__before" style={{ clipPath: `inset(0 ${100 - pos}% 0 0)` }}>
            <BAImage variant="before" fit={fits[activeFit]} />
            <div className="ba__tag ba__tag--before chip">BEFORE</div>
          </div>
          <div className="ba__handle" style={{ left: `${pos}%` }}>
            <div className="ba__handle-line" />
            <div className="ba__handle-knob">
              <span>‹</span><span>›</span>
            </div>
          </div>
        </div>

        <div className="ba__fits reveal delay-3">
          {fits.map((f, i) => (
            <button
              key={i}
              className={`ba__fit ${activeFit === i ? "is-active" : ""}`}
              onClick={() => setActiveFit(i)}
            >
              <span className="ba__fit-dot" style={{ background: f.color }} />
              <span className="label">{f.name}</span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

function BAImage({ variant, fit }) {
  const isAfter = variant === "after";
  return (
    <div className="ba__img">
      <div className="ba__bg" style={{ background: isAfter ? "var(--yellow)" : "var(--cream)" }}>
        <svg viewBox="0 0 400 500" width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
          <defs>
            <pattern id={`dots-${variant}`} x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse">
              <circle cx="5" cy="5" r={isAfter ? "1.6" : "1.2"} fill={isAfter ? "var(--pink)" : "var(--blue)"} opacity="0.55"/>
            </pattern>
          </defs>
          <rect width="400" height="500" fill={`url(#dots-${variant})`} opacity="0.55"/>

          <ellipse cx="200" cy="140" rx="62" ry="78" fill={isAfter ? "var(--pink)" : "var(--blue)"}/>
          <path d="M138 130 Q 140 70, 200 60 Q 260 70, 262 130 Q 250 100, 200 100 Q 150 100, 138 130 Z" fill="var(--blue)"/>
          <rect x="184" y="200" width="32" height="34" fill={isAfter ? "var(--pink)" : "var(--blue)"}/>

          {isAfter ? (
            <Garment fit={fit} />
          ) : (
            <path d="M120 250 L 200 230 L 280 250 L 290 320 L 260 340 L 260 460 L 140 460 L 140 340 L 110 320 Z"
              fill="var(--cream-deep, #ECE3CC)" stroke="var(--blue)" strokeWidth="3" strokeLinejoin="round"/>
          )}

          <rect width="400" height="500" fill={`url(#dots-${variant})`} opacity="0.25"/>
        </svg>
      </div>
    </div>
  );
}

function Garment({ fit }) {
  if (fit.garment === "parka") {
    return (
      <>
        <path d="M100 240 L 200 220 L 300 240 L 320 340 L 290 360 L 290 470 L 110 470 L 110 360 L 80 340 Z"
          fill={fit.color} stroke="var(--blue)" strokeWidth="3" strokeLinejoin="round"/>
        <path d="M180 220 Q 200 210, 220 220 L 230 280 L 170 280 Z" fill="var(--cream)" stroke="var(--blue)" strokeWidth="2"/>
        <line x1="200" y1="240" x2="200" y2="470" stroke="var(--cream)" strokeWidth="3"/>
        {[260, 320, 380, 440].map(y => <circle key={y} cx="200" cy={y} r="4" fill="var(--cream)"/>)}
      </>
    );
  }
  if (fit.garment === "tank") {
    return (
      <>
        <path d="M150 240 L 200 230 L 250 240 L 268 320 L 252 340 L 252 460 L 148 460 L 148 340 L 132 320 Z"
          fill={fit.color} stroke="var(--blue)" strokeWidth="3" strokeLinejoin="round"/>
        {Array.from({ length: 80 }).map((_, i) => {
          const x = 150 + (i % 8) * 14;
          const y = 250 + Math.floor(i / 8) * 22;
          return <circle key={i} cx={x} cy={y} r="2" fill="var(--blue)" opacity="0.45"/>;
        })}
      </>
    );
  }
  return (
    <>
      <path d="M120 250 L 200 230 L 280 250 L 290 320 L 260 340 L 260 460 L 140 460 L 140 340 L 110 320 Z"
        fill={fit.color} stroke="var(--blue)" strokeWidth="3" strokeLinejoin="round"/>
      <text x="200" y="370" textAnchor="middle" fontFamily="Anton, sans-serif" fontSize="38" fill="var(--cream)" letterSpacing="2">TRYON</text>
      <text x="200" y="402" textAnchor="middle" fontFamily="Anton, sans-serif" fontSize="38" fill="var(--cream)" letterSpacing="2">ME ‘26</text>
    </>
  );
}

function Features() {
  const features = [
    { num: "A", title: "Auto-detect garment", body: "iOS Subject Lifter pulls the clothes out of any screenshot. No cropping, no stickers.", color: "var(--pink)" },
    { num: "B", title: "Manual crop fallback", body: "Eight-handle box, dimmed surround. For when the AI gets a bit too generous.", color: "var(--yellow)" },
    { num: "C", title: "Before / after compare", body: "Slider in every result. Side by side or full screen — your call.", color: "var(--blue)" },
    { num: "D", title: "5 free credits", body: "On sign-up, no card. Top up with credit packs or promo codes.", color: "var(--pink)" },
    { num: "E", title: "Save · Share · Delete", body: "Long-press in History. Outfits stay on-device unless you share them.", color: "var(--yellow)" },
    { num: "F", title: "On-device first", body: "Photos and history live in your phone. Cloud opt-in, never the default.", color: "var(--blue)" },
  ];
  return (
    <section className="section" id="features">
      <div className="container">
        <div className="section__head reveal">
          <span className="num">§</span>
          <Eyebrow>WHAT'S INSIDE</Eyebrow>
          <hr style={{ flex: 1, border: "none", height: 2, background: "var(--blue)" }}/>
          <Eyebrow color="var(--blue)">FEATURES · vol.1</Eyebrow>
        </div>
        <h2 className="display reveal" style={{ fontSize: "clamp(40px, 6vw, 80px)", maxWidth: 900, marginBottom: 40 }}>
          <Misreg text="SIX BUTTONS." />
          <br />
          <span style={{ color: "var(--pink)" }}>NO BLOAT.</span>
        </h2>
        <div className="features">
          {features.map((f, i) => (
            <div key={i} className="feature reveal" style={{ transitionDelay: `${(i % 3) * 80}ms` }}>
              <div className="feature__num display" style={{ color: f.color }}>{f.num}</div>
              <div className="feature__title display">{f.title}</div>
              <p className="feature__body">{f.body}</p>
              <div className="feature__rule" />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Extension() {
  return (
    <section className="section section--ext" id="extension">
      <div className="container ext">
        <div className="ext__copy reveal">
          <span className="chip chip--filled" style={{ marginBottom: 18 }}>CHROME · NEW</span>
          <h2 className="display" style={{ fontSize: "clamp(42px, 6.5vw, 92px)" }}>
            <Misreg text="RIGHT-CLICK" color="pink" />
            <br />
            <Misreg text="ANY OUTFIT." />
          </h2>
          <p style={{ marginTop: 20, fontSize: 18, maxWidth: 480 }}>
            Browsing on desktop? Right-click any clothing image — ASOS, SSENSE, Depop, IG, you name it —
            hit <strong>Try on with TryOnMe</strong>. The fit ships to your phone in seconds.
          </p>
          <div style={{ marginTop: 26, display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a className="btn btn--blue" href="#"><svg viewBox="0 0 24 24" className="icon" fill="currentColor"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" strokeWidth="2"/><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>ADD TO CHROME</a>
            <a className="btn btn--ghost" href="#">SEE IT IN ACTION</a>
          </div>
          <ul className="ext__list">
            <li>★ Works on every site that loads images</li>
            <li>★ Sign in with Google — same account as the app</li>
            <li>★ Unlimited storage of try-ons in your library</li>
          </ul>
        </div>

        <div className="ext__art reveal delay-1">
          <ExtensionMockup />
        </div>
      </div>
    </section>
  );
}

function ExtensionMockup() {
  return (
    <div className="extmock">
      <div className="extmock__bar">
        <span className="extmock__dot" style={{ background: "#FF4D8B" }}/>
        <span className="extmock__dot" style={{ background: "#FFC83D" }}/>
        <span className="extmock__dot" style={{ background: "#2D3D7A" }}/>
        <div className="extmock__url">depop.com/p/cropped-leather-jacket</div>
      </div>
      <div className="extmock__page">
        <div className="extmock__product">
          <svg viewBox="0 0 240 320" width="100%">
            <rect width="240" height="320" fill="var(--cream-deep, #ECE3CC)"/>
            <path d="M50 80 L 90 50 L 150 50 L 190 80 L 200 140 L 180 160 V 280 H 60 V 160 L 40 140 Z"
              fill="var(--pink)" stroke="var(--blue)" strokeWidth="3" strokeLinejoin="round"/>
            <path d="M90 50 L 120 80 L 150 50" fill="var(--cream)" stroke="var(--blue)" strokeWidth="2"/>
            {Array.from({ length: 60 }).map((_, i) => (
              <circle key={i} cx={50 + (i % 10) * 14} cy={70 + Math.floor(i / 10) * 35} r="1.4" fill="var(--blue)" opacity="0.4"/>
            ))}
          </svg>
        </div>
        <div className="extmock__menu">
          <div className="extmock__mi">Open image in new tab</div>
          <div className="extmock__mi">Save image as…</div>
          <div className="extmock__mi">Copy image</div>
          <div className="extmock__mi extmock__mi--hl">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <circle cx="12" cy="12" r="10"/>
            </svg>
            Try on with TryOnMe
          </div>
          <div className="extmock__mi">Inspect</div>
        </div>
        <div className="extmock__cursor">
          <svg viewBox="0 0 24 24" width="22" height="22"><path d="M3 2 L 21 12 L 12 14 L 8 22 Z" fill="var(--blue)" stroke="var(--cream)" strokeWidth="1.5"/></svg>
        </div>
      </div>
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
window.Features = Features;
window.Extension = Extension;
