/* ===== PLAYGROUND — interactive toys ===== */

const Doodle = () => {
  const canvasRef = React.useRef<SVGSVGElement | null>(null);
  const [color, setColor] = React.useState("#1a1814");
  const drawing = React.useRef(false);
  const last = React.useRef<Nullable<{ x: number; y: number }>>(null);

  const getPos = (e: React.MouseEvent<SVGSVGElement> | React.TouchEvent<SVGSVGElement>) => {
    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return { x: 0, y: 0 };
    const isTouch = "touches" in e;
    const t = isTouch ? e.touches?.[0] : null;
    const clientX = t ? t.clientX : (e as React.MouseEvent<SVGSVGElement>).clientX;
    const clientY = t ? t.clientY : (e as React.MouseEvent<SVGSVGElement>).clientY;
    return {
      x: clientX - rect.left,
      y: clientY - rect.top,
    };
  };

  const start = (e: React.MouseEvent<SVGSVGElement> | React.TouchEvent<SVGSVGElement>) => {
    drawing.current = true;
    last.current = getPos(e);
  };
  const move = (e: React.MouseEvent<SVGSVGElement> | React.TouchEvent<SVGSVGElement>) => {
    if (!drawing.current) return;
    e.preventDefault();
    const p = getPos(e);
    const svg = canvasRef.current;
    if (!svg || !last.current) return;
    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    line.setAttribute("x1", String(last.current.x));
    line.setAttribute("y1", String(last.current.y));
    line.setAttribute("x2", String(p.x));
    line.setAttribute("y2", String(p.y));
    line.setAttribute("stroke", color);
    line.setAttribute("stroke-width", "2.4");
    line.setAttribute("stroke-linecap", "round");
    svg.appendChild(line);
    last.current = p;
  };
  const end = () => { drawing.current = false; };
  const clear = () => {
    if (canvasRef.current) canvasRef.current.innerHTML = "";
  };

  const colors = ["#1a1814", "#d9a441", "#c94a3f", "#4a6fa5", "#6b8e4e"];

  return (
    <div className="play-card play-doodle">
      <div className="head">
        <span>TOY 01 · SCRATCHPAD</span>
        <div className="dot-row"><span/><span/><span/></div>
      </div>
      <h3>Leave a doodle.</h3>
      <svg
        ref={canvasRef}
        className="doodle-canvas"
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end}
      />
      <div className="ctrls">
        {colors.map((c) => (
          <div key={c} className="swatch"
            style={{ background: c, outline: color === c ? "2px solid var(--ochre)" : "none", outlineOffset: 2 }}
            onClick={() => setColor(c)} />
        ))}
        <button onClick={clear} style={{ marginLeft: "auto" }}>Clear</button>
      </div>
    </div>
  );
};

const ColorPick = () => {
  const palettes: Array<{ name: string; val: string }> = [
    { name: "paper", val: "#f6f0e3" },
    { name: "ochre", val: "#d9a441" },
    { name: "ink",   val: "#1a1814" },
    { name: "brick", val: "#c94a3f" },
    { name: "slate", val: "#4a6fa5" },
    { name: "moss",  val: "#6b8e4e" },
    { name: "sand",  val: "#e8d5a0" },
    { name: "wine",  val: "#7a2e38" },
  ];
  const [picked, setPicked] = React.useState(palettes[1]);

  return (
    <div className="play-card play-color">
      <div className="head" style={{ color: "var(--paper)", opacity: 0.7 }}>
        <span>TOY 02 · PALETTE</span>
        <div className="dot-row"><span style={{borderColor:"var(--paper)"}}/><span style={{borderColor:"var(--paper)"}}/><span style={{borderColor:"var(--paper)"}}/></div>
      </div>
      <h3 style={{ color: "var(--paper)" }}>My working palette.</h3>
      <div className="color-pick">
        {palettes.map((p) => (
          <div key={p.name} className="sw"
            style={{ background: p.val, outline: picked.name === p.name ? "2px solid var(--ochre)" : "none", outlineOffset: -4 }}
            onClick={() => setPicked(p)}>
            {p.name}
          </div>
        ))}
      </div>
      <div className="color-out" style={{ color: "var(--paper)" }}>
        <span>SELECTED</span>
        <span>{picked.val.toUpperCase()} · {picked.name}</span>
      </div>
    </div>
  );
};

const DragStack = () => {
  const items = [
    { title: "Research", body: "5 calls. 1 insight. Ship it." },
    { title: "Design", body: "Pixel-precise. Every margin earned." },
    { title: "Build", body: "Typed. Tested. Deployed Friday." },
    { title: "Iterate", body: "Week-2 review, metrics in hand." },
  ];
  const [order, setOrder] = React.useState(items.map((_, i) => i));

  const send = () => {
    setOrder((o) => [...o.slice(1), o[0]]);
  };

  return (
    <div className="play-card play-drag">
      <div className="head">
        <span>TOY 03 · DECK</span>
        <div className="dot-row"><span/><span/><span/></div>
      </div>
      <h3>Shuffle the deck.</h3>
      <div className="stack-dragger">
        {order.map((idx, pos) => {
          const top = items[idx];
          const offset = (order.length - 1 - pos);
          return (
            <div
              key={idx}
              className="drag-card"
              onClick={pos === order.length - 1 ? send : undefined}
              style={{
                transform: `translate(${offset * 6}px, ${-offset * 6}px) rotate(${(offset - 1.5) * 2}deg)`,
                zIndex: pos,
                boxShadow: pos === order.length - 1 ? "4px 4px 0 var(--ochre)" : "none",
                cursor: pos === order.length - 1 ? "pointer" : "default",
              }}
            >
              <div className="big">{top.title}</div>
              <div>{top.body}</div>
              <div style={{ marginTop: 16, opacity: 0.6 }}>
                {pos === order.length - 1 ? "↓ click to send to back" : "\u00A0"}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const Synth = () => {
  const rows = 4;
  const cols = 12;
  const [grid, setGrid] = React.useState(() => Array(rows * cols).fill(false));
  const [step, setStep] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setStep((s) => (s + 1) % cols), 180);
    return () => clearInterval(id);
  }, [playing]);

  const toggle = (i: number) => {
    setGrid((g) => g.map((v, j) => (j === i ? !v : v)));
  };

  return (
    <div className="play-card play-synth">
      <div className="head">
        <span>TOY 04 · SEQUENCER</span>
        <div className="dot-row"><span/><span/><span/></div>
      </div>
      <h3>Tap cells. I like patterns.</h3>
      <div className="synth-grid">
        {Array.from({ length: rows }).map((_, r) =>
          Array.from({ length: cols }).map((_, c) => {
            const i = r * cols + c;
            const active = grid[i];
            const isStep = playing && step === c;
            return (
              <div
                key={i}
                className={`synth-cell ${active ? "on" : ""}`}
                onClick={() => toggle(i)}
                style={{
                  boxShadow: isStep ? "inset 0 0 0 2px var(--ochre-deep)" : "none",
                  background: active ? "var(--ink)" : isStep ? "rgba(26,24,20,0.15)" : undefined,
                }}
              />
            );
          })
        )}
      </div>
      <div className="synth-ctrls">
        <button onClick={() => setPlaying((p) => !p)}
          style={{ padding: "8px 16px", border: "1.5px solid var(--ink)", borderRadius: 999, background: "var(--paper)" }}>
          {playing ? "■ STOP" : "▶ PLAY"}
        </button>
        <span>{grid.filter(Boolean).length} cells · step {step + 1}/12</span>
        <button onClick={() => setGrid(Array(rows * cols).fill(false))}
          style={{ padding: "8px 16px", border: "1.5px solid var(--ink)", borderRadius: 999, background: "var(--paper)" }}>
          Clear
        </button>
      </div>
    </div>
  );
};

const LiveScribble = () => {
  const [density, setDensity] = React.useState(8);
  const [version, setVersion] = React.useState(0);
  const seed = React.useRef(Math.random());
  const paths = React.useMemo(() => {
    const rand = (s: number) => {
      let t = s;
      return () => { t = (t * 9301 + 49297) % 233280; return t / 233280; };
    };
    const r = rand(Math.floor(seed.current * 10000));
    return Array.from({ length: density }).map(() => {
      const x1 = r() * 300, y1 = r() * 200;
      const x2 = r() * 300, y2 = r() * 200;
      const cx = (x1 + x2) / 2 + (r() - 0.5) * 80;
      const cy = (y1 + y2) / 2 + (r() - 0.5) * 80;
      return `M ${x1} ${y1} Q ${cx} ${cy}, ${x2} ${y2}`;
    });
  }, [density, version]);

  return (
    <div className="play-card play-scribble">
      <div className="head">
        <span>TOY 05 · SCRIBBLE LAB</span>
        <div className="dot-row"><span/><span/><span/></div>
      </div>
      <h3>Generate. Regenerate. Ship.</h3>
      <div style={{ background: "var(--paper-deep)", border: "1px dashed var(--rule)", height: 180, position: "relative" }}>
        <svg viewBox="0 0 300 200" width="100%" height="100%" style={{ display: "block" }}>
          {paths.map((d, i) => (
            <path key={i} d={d} fill="none" stroke={i % 3 === 0 ? "var(--ochre-deep)" : "var(--ink)"} strokeWidth={1 + (i % 2) * 0.5} strokeLinecap="round" opacity={0.7} />
          ))}
        </svg>
      </div>
      <div className="ctrls" style={{ alignItems: "center" }}>
        <span style={{ fontSize: 11 }}>DENSITY</span>
        <input type="range" min="2" max="30" value={density} onChange={(e) => setDensity(+e.target.value)} style={{ flex: 1 }} />
        <button onClick={() => { seed.current = Math.random(); setVersion((v) => v + 1); }} style={{ padding: "6px 14px", border: "1px solid var(--ink)", borderRadius: 999 }}>
          Regenerate
        </button>
      </div>
    </div>
  );
};

const Playground = () => (
  <section className="section shell" id="play" data-screen-label="06 Playground">
    <div className="section-head reveal">
      <span className="num">§06</span>
      <h2 className="title">The <em style={{fontFamily:"var(--font-hand)", color:"var(--ochre-deep)"}}>playground</em></h2>
      <span className="meta">5 toys · click around</span>
    </div>
    <div className="play-grid">
      <Doodle />
      <ColorPick />
      <DragStack />
      <Synth />
      <LiveScribble />
    </div>
  </section>
);

/* ===== CTA + FOOTER ===== */
const CTA = () => (
  <section id="contact" data-screen-label="07 Contact">
    <div className="shell">
      <div className="cta-wrap">
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.15em",
          textTransform: "uppercase", color: "var(--ink-faint)", marginBottom: 20,
        }}>
          ——— §07 · the part where you email me
        </div>
        <h2 className="cta-title">
          Got a thing<br />
          to <span style={{ position: "relative", display: "inline-block" }}>
            build?
            <CircleScribble style={{ position: "absolute", inset: "-8%", width: "116%", height: "116%", pointerEvents: "none" }} color="var(--ochre-deep)" />
          </span><br />
          <em>let's talk.</em>
        </h2>
        <a href="#" className="cta-btn">
          Book a 20-min intro call <ArrowRight size={16} />
        </a>
        <div className="cta-sub">No pitch deck. No filler. Just the problem.</div>
      </div>

      <div className="foot">
        <div>© 2026 · Aditya Thorat · Built with ink, pixels, and chai</div>
        <div className="foot-links">
          <a href="#">Twitter/X</a>
          <a href="#">LinkedIn</a>
          <a href="#">GitHub</a>
          <a href="#">Instagram</a>
          <a href="#">Read.cv</a>
          <a href="#">Are.na</a>
        </div>
      </div>
    </div>
  </section>
);

Object.assign(window, { Playground, CTA });
