/* global React, I, UI */
// =============== กระดานวาดภาพในแชท — รองรับ Apple Pencil / นิ้ว / เมาส์ ===============
const { useState: useStateDR, useEffect: useEffectDR, useRef: useRefDR } = React;

const DR_COLORS = ["#0c0a09", "#dc2626", "#2563eb", "#16a34a", "#f59e0b", "#9333ea"];
const DR_SIZES = [2.5, 5, 10];

function ChatDrawModal({ onClose, onDone }) {
  const { Btn } = window.UI;
  const canvasRef = useRefDR(null);
  const wrapRef = useRefDR(null);
  const strokesRef = useRefDR([]);   // [{color, w, erase, pts:[{x,y,p}]}]
  const liveRef = useRefDR(null);
  const [color, setColor] = useStateDR(DR_COLORS[0]);
  const [size, setSize] = useStateDR(DR_SIZES[1]);
  const [eraser, setEraser] = useStateDR(false);
  const [, force] = useStateDR(0);

  const dpr = window.devicePixelRatio || 1;

  const repaint = () => {
    const c = canvasRef.current;
    if (!c) return;
    const ctx = c.getContext("2d");
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, c.width / dpr, c.height / dpr);
    const all = liveRef.current ? [...strokesRef.current, liveRef.current] : strokesRef.current;
    all.forEach(s => {
      ctx.strokeStyle = s.erase ? "#ffffff" : s.color;
      ctx.lineCap = "round"; ctx.lineJoin = "round";
      const pts = s.pts;
      for (let i = 1; i < pts.length; i++) {
        ctx.beginPath();
        ctx.lineWidth = s.w * (s.erase ? 3 : (pts[i].p || 1));
        ctx.moveTo(pts[i - 1].x, pts[i - 1].y);
        ctx.lineTo(pts[i].x, pts[i].y);
        ctx.stroke();
      }
      if (pts.length === 1) {
        ctx.fillStyle = s.erase ? "#ffffff" : s.color;
        ctx.beginPath();
        ctx.arc(pts[0].x, pts[0].y, (s.w * (pts[0].p || 1)) / 2, 0, Math.PI * 2);
        ctx.fill();
      }
    });
  };

  useEffectDR(() => {
    const c = canvasRef.current, wrap = wrapRef.current;
    if (!c || !wrap) return;
    const rect = wrap.getBoundingClientRect();
    c.width = Math.round(rect.width * dpr);
    c.height = Math.round(rect.height * dpr);
    c.style.width = rect.width + "px";
    c.style.height = rect.height + "px";
    repaint();
  }, []);

  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    return { x: e.clientX - r.left, y: e.clientY - r.top, p: e.pressure && e.pressure > 0 ? 0.4 + e.pressure * 1.2 : 1 };
  };

  const down = (e) => {
    e.preventDefault();
    canvasRef.current.setPointerCapture(e.pointerId);
    liveRef.current = { color, w: size, erase: eraser, pts: [pos(e)] };
    repaint();
  };
  const move = (e) => {
    if (!liveRef.current) return;
    e.preventDefault();
    // ใช้ coalesced events ให้เส้นลื่นบน iPad
    const evs = e.getCoalescedEvents ? e.getCoalescedEvents() : [e];
    evs.forEach(ev => liveRef.current.pts.push(pos(ev)));
    repaint();
  };
  const up = () => {
    if (!liveRef.current) return;
    strokesRef.current = [...strokesRef.current, liveRef.current];
    liveRef.current = null;
    force(n => n + 1);
    repaint();
  };

  const undo = () => { strokesRef.current = strokesRef.current.slice(0, -1); force(n => n + 1); repaint(); };
  const clearAll = () => { strokesRef.current = []; liveRef.current = null; force(n => n + 1); repaint(); };

  const send = () => {
    if (strokesRef.current.length === 0) { window.toast && window.toast("ยังไม่ได้วาดอะไรเลย"); return; }
    onDone(canvasRef.current.toDataURL("image/jpeg", 0.85));
    onClose();
  };

  return (
    <div className="scrim" style={{display: "flex", alignItems: "center", justifyContent: "center", padding: 14, zIndex: 320}} onClick={onClose}>
      <div style={{background: "var(--surface)", borderRadius: 14, width: 720, maxWidth: "97vw", display: "flex", flexDirection: "column", overflow: "hidden"}} onClick={e => e.stopPropagation()}>
        <div style={{padding: "13px 18px 10px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10}}>
          <div style={{flex: 1}}>
            <div style={{fontSize: 15, fontWeight: 700}}>วาดภาพส่งในแชท</div>
            <div style={{fontSize: 11.5, color: "var(--ink-3)"}}>รองรับ Apple Pencil / นิ้วบน iPad — กดน้ำหนักปากกาได้</div>
          </div>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>

        {/* toolbar */}
        <div style={{padding: "8px 14px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", background: "var(--surface-2)"}}>
          <div style={{display: "flex", gap: 5}}>
            {DR_COLORS.map(cl => (
              <button key={cl} onClick={() => { setColor(cl); setEraser(false); }} title={cl}
                style={{width: 26, height: 26, borderRadius: "50%", background: cl, cursor: "pointer",
                  border: !eraser && color === cl ? "2.5px solid var(--surface)" : "2px solid transparent",
                  boxShadow: !eraser && color === cl ? `0 0 0 2px ${cl}` : "none"}}></button>
            ))}
          </div>
          <div style={{width: 1, height: 22, background: "var(--line-strong)"}}></div>
          <div style={{display: "flex", gap: 5, alignItems: "center"}}>
            {DR_SIZES.map(s => (
              <button key={s} onClick={() => setSize(s)} title={`ขนาดเส้น ${s}px`}
                style={{width: 30, height: 30, borderRadius: 8, cursor: "pointer", display: "grid", placeItems: "center",
                  border: size === s ? "1.5px solid var(--ink-1)" : "1px solid var(--line)", background: size === s ? "var(--surface-3)" : "var(--surface)"}}>
                <span style={{width: s + 3, height: s + 3, borderRadius: "50%", background: "var(--ink-1)", display: "block"}}></span>
              </button>
            ))}
          </div>
          <div style={{width: 1, height: 22, background: "var(--line-strong)"}}></div>
          <button className={`btn sm ${eraser ? "primary" : ""}`} onClick={() => setEraser(v => !v)}>ยางลบ</button>
          <button className="btn sm" onClick={undo} disabled={strokesRef.current.length === 0}>↩ ย้อนกลับ</button>
          <button className="btn sm" onClick={clearAll}>ล้างกระดาน</button>
        </div>

        {/* canvas */}
        <div ref={wrapRef} style={{height: "min(52vh, 430px)", background: "white", cursor: "crosshair"}}>
          <canvas ref={canvasRef}
            onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} onPointerLeave={up}
            style={{touchAction: "none", display: "block"}}></canvas>
        </div>

        <div style={{padding: "11px 18px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", display: "flex", gap: 8, justifyContent: "flex-end"}}>
          <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
          <Btn kind="primary" icon={I.send} onClick={send}>แนบภาพวาดลงแชท</Btn>
        </div>
      </div>
    </div>
  );
}

window.ChatDrawModal = ChatDrawModal;
