/* Cuaderno de obra: compositor con modo Escribir / Dibujar. El dibujo es papel
   cuadriculado a mano alzada; los trazos se guardan como LISTA DE PUNTOS (JSON),
   no como bitmap — por eso deshacer es un pop() y se rasteriza al mostrar. */
const { useState, useEffect, useRef, useCallback } = React;

const LAPICES = [
  { id: 'ink', col: '#2d2620', label: 'Lápiz' },
  { id: 'sage', col: '#7d9159', label: 'Medidas' },
  { id: 'coral', col: '#c56a3f', label: 'Ojo con esto' },
];
const GRUESOS = [{ id: 'fino', w: 1.8 }, { id: 'medio', w: 3.2 }, { id: 'grueso', w: 6 }];
const PAPEL = '#fdfaf4';
const TIPOS = ['nota', 'medida', 'precio', 'problema', 'idea'];

// Pinta trazos (y opcionalmente la cuadrícula) en un canvas, escalando por DPR.
function pintarEn(canvas, trazos) {
  const g = canvas.getContext('2d');
  const r = window.devicePixelRatio || 1;
  if (canvas.width !== canvas.clientWidth * r) { canvas.width = canvas.clientWidth * r; canvas.height = canvas.clientHeight * r; }
  g.setTransform(r, 0, 0, r, 0, 0);
  g.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
  g.strokeStyle = 'rgba(45,38,32,.06)'; g.lineWidth = 1;
  for (let x = 20; x < canvas.clientWidth; x += 20) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, canvas.clientHeight); g.stroke(); }
  for (let y = 20; y < canvas.clientHeight; y += 20) { g.beginPath(); g.moveTo(0, y); g.lineTo(canvas.clientWidth, y); g.stroke(); }
  g.lineCap = 'round'; g.lineJoin = 'round';
  for (const t of trazos) {
    if (!t.pts || t.pts.length < 2) continue;
    g.strokeStyle = t.goma ? PAPEL : t.col;
    g.lineWidth = t.goma ? t.w * 4 : t.w;
    g.beginPath(); g.moveTo(t.pts[0].x, t.pts[0].y);
    for (let i = 1; i < t.pts.length; i++) g.lineTo(t.pts[i].x, t.pts[i].y);
    g.stroke();
  }
}

// Lienzo interactivo. Al guardar entrega el ARRAY de trazos (no un data URL).
function Lienzo({ alto = 280, onGuardar, busy }) {
  const ref = useRef(null);
  const trazos = useRef([]);
  const activo = useRef(null);
  const [lapiz, setLapiz] = useState('ink');
  const [grueso, setGrueso] = useState('medio');
  const [goma, setGoma] = useState(false);
  const [vacio, setVacio] = useState(true);

  const pintar = () => { if (ref.current) pintarEn(ref.current, trazos.current); };
  useEffect(() => { pintar(); }, []);

  const punto = (ev) => { const r = ref.current.getBoundingClientRect(); return { x: ev.clientX - r.left, y: ev.clientY - r.top }; };
  const abajo = (ev) => {
    ev.currentTarget.setPointerCapture(ev.pointerId);
    activo.current = { col: LAPICES.find((l) => l.id === lapiz).col, w: GRUESOS.find((g) => g.id === grueso).w, goma, pts: [punto(ev)] };
    trazos.current.push(activo.current); setVacio(false);
  };
  const mover = (ev) => { if (!activo.current) return; activo.current.pts.push(punto(ev)); pintar(); };
  const arriba = () => { activo.current = null; };
  const deshacer = () => { trazos.current.pop(); setVacio(!trazos.current.length); pintar(); };
  const limpiar = () => { trazos.current = []; setVacio(true); pintar(); };

  const chip = (activoBool) => ({
    display: 'flex', alignItems: 'center', gap: 6, padding: '5px 10px 5px 6px', border: 0, borderRadius: 999, cursor: 'pointer',
    background: activoBool ? 'var(--olive-tint)' : 'var(--paper-2)',
  });

  return (
    <div style={{ display: 'grid', gap: 10 }}>
      <div style={{ position: 'relative', borderRadius: 12, overflow: 'hidden', background: PAPEL, boxShadow: 'inset 0 1px 3px rgba(45,38,32,.12)' }}>
        <canvas ref={ref} onPointerDown={abajo} onPointerMove={mover} onPointerUp={arriba} onPointerLeave={arriba}
          style={{ display: 'block', width: '100%', height: alto, touchAction: 'none', cursor: 'crosshair' }} />
        {vacio && (
          <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', pointerEvents: 'none', fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 15, color: '#8a7e72', opacity: 0.75 }}>
            Dibuja acá: la planta, el mueble, dónde va el enchufe
          </span>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
        {LAPICES.map((l) => (
          <button key={l.id} onClick={() => { setLapiz(l.id); setGoma(false); }} style={chip(lapiz === l.id && !goma)}>
            <span style={{ width: 13, height: 13, borderRadius: 999, background: l.col }} />
            <span style={{ fontSize: 11 }}>{l.label}</span>
          </button>
        ))}
        <span style={{ display: 'flex', gap: 4, marginLeft: 4 }}>
          {GRUESOS.map((g) => (
            <button key={g.id} onClick={() => setGrueso(g.id)} style={{ display: 'grid', placeItems: 'center', width: 28, height: 28, border: 0, borderRadius: 999, cursor: 'pointer', background: grueso === g.id ? 'var(--olive-tint)' : 'var(--paper-2)' }}>
              <span style={{ width: g.w * 2.2, height: g.w * 2.2, borderRadius: 999, background: 'var(--ink)' }} />
            </button>
          ))}
        </span>
        <button onClick={() => setGoma((x) => !x)} style={{ border: 0, borderRadius: 999, padding: '5px 11px', fontSize: 11, cursor: 'pointer', background: goma ? 'var(--olive)' : 'var(--paper-2)', color: goma ? '#fff' : 'var(--ink-3)' }}>Goma</button>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 7, alignItems: 'center' }}>
          <button className="btn" onClick={deshacer} title="Deshacer" style={{ padding: '6px 10px' }}><Icon name="chevronLeft" size={14} /></button>
          <button className="btn" onClick={limpiar} style={{ padding: '6px 10px' }}>Limpiar</button>
          <button className="btn olive" disabled={vacio || busy} onClick={() => onGuardar(trazos.current.slice())} style={{ padding: '6px 12px' }}>
            <Icon name="check" size={14} /> {busy ? 'Guardando…' : 'Guardar el bosquejo'}
          </button>
        </span>
      </div>
    </div>
  );
}

// Render de solo lectura de un bosquejo guardado.
function BosquejoMini({ trazos, alto = 170 }) {
  const ref = useRef(null);
  useEffect(() => { if (ref.current) pintarEn(ref.current, trazos || []); }, [trazos]);
  return (
    <div style={{ borderRadius: 10, overflow: 'hidden', background: PAPEL, boxShadow: 'inset 0 1px 3px rgba(45,38,32,.1)' }}>
      <canvas ref={ref} style={{ display: 'block', width: '100%', height: alto }} />
    </div>
  );
}

function Composer({ proyectoId, onGuardado }) {
  const [modo, setModo] = useState('escribir');
  const [texto, setTexto] = useState('');
  const [tipo, setTipo] = useState('nota');
  const [busy, setBusy] = useState(false);

  const pill = (activo) => ({
    display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 14px', border: 0, borderRadius: 999, cursor: 'pointer',
    fontSize: 13, fontWeight: activo ? 600 : 500, background: activo ? 'var(--olive-tint)' : 'transparent', color: activo ? 'var(--olive-2)' : 'var(--ink-3)',
  });

  const anotar = async () => {
    if (!texto.trim() || busy) return;
    setBusy(true);
    try { await window.api(`/api/proyectos/${proyectoId}/anotaciones`, { method: 'POST', body: JSON.stringify({ tipo, texto: texto.trim() }) }); setTexto(''); onGuardado(); }
    catch (e) { alert(e.message); } finally { setBusy(false); }
  };
  const guardarDibujo = async (trazos) => {
    setBusy(true);
    try { await window.api(`/api/proyectos/${proyectoId}/anotaciones`, { method: 'POST', body: JSON.stringify({ tipo: 'dibujo', texto: texto.trim() || null, trazos }) }); setTexto(''); onGuardado(); }
    catch (e) { alert(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="card" style={{ padding: 16, display: 'grid', gap: 12 }}>
      <div style={{ display: 'flex', gap: 6 }}>
        <button style={pill(modo === 'escribir')} onClick={() => setModo('escribir')}><Icon name="edit" size={15} /> Escribir</button>
        <button style={pill(modo === 'dibujar')} onClick={() => setModo('dibujar')}><Icon name="chart" size={15} /> Dibujar</button>
      </div>
      <textarea value={texto} onChange={(e) => setTexto(e.target.value)} rows={modo === 'dibujar' ? 1 : 2}
        placeholder={modo === 'dibujar' ? 'Qué es este dibujo (opcional)' : 'Anotá algo de la obra…'}
        style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 12, border: '1px solid var(--line)', background: 'var(--card-elev)', color: 'var(--ink)', fontSize: 14, fontFamily: 'inherit', resize: 'vertical' }} />
      {modo === 'escribir' ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
            {TIPOS.map((t) => (
              <button key={t} onClick={() => setTipo(t)} style={{ border: 0, borderRadius: 999, padding: '4px 10px', fontSize: 12, cursor: 'pointer', background: tipo === t ? 'var(--olive)' : 'var(--paper-2)', color: tipo === t ? '#fff' : 'var(--ink-3)' }}>{t}</button>
            ))}
          </div>
          <button className="btn olive" onClick={anotar} disabled={busy} style={{ marginLeft: 'auto' }}><Icon name="check" size={14} /> Anotar</button>
        </div>
      ) : (
        <Lienzo onGuardar={guardarDibujo} busy={busy} />
      )}
    </div>
  );
}

function CuadernoView() {
  const [data, setData] = useState(null);
  const [err, setErr] = useState('');
  const [proy, setProy] = useState(null);
  const [anotaciones, setAnotaciones] = useState([]);

  useEffect(() => {
    window.api('/api/proyectos/app-data')
      .then((d) => { setData(d); if (d.proyectos?.length) setProy(d.proyectos[0].id); })
      .catch((e) => setErr(e.message));
  }, []);

  const cargar = useCallback(async (pid) => {
    try { setAnotaciones(await window.api(`/api/proyectos/${pid}/anotaciones`)); }
    catch { setAnotaciones([]); }
  }, []);
  useEffect(() => { if (proy) cargar(proy); }, [proy, cargar]);

  if (err) return <div className="card" style={{ padding: 18, color: 'var(--rust)' }}>No se pudo cargar: {err}</div>;
  if (!data) return <div style={{ color: 'var(--ink-3)' }}>Cargando…</div>;
  if (!(data.proyectos || []).length) {
    return <div className="card" style={{ padding: 40, textAlign: 'center', maxWidth: 460, margin: '30px auto' }}>
      <h2 style={{ fontSize: 18, margin: '0 0 6px' }}>El cuaderno es de un proyecto</h2>
      <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: 0 }}>Creá un proyecto primero, en la pestaña Proyectos.</p>
    </div>;
  }

  return (
    <div>
      <h1 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 26, margin: '0 0 4px' }}>Cuaderno de obra</h1>
      <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '0 0 18px' }}>Notas, medidas y bosquejos a mano del proyecto.</p>

      <div className="card" style={{ padding: '12px 16px', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Proyecto:</span>
          {data.proyectos.map((x) => (
            <button key={x.id} onClick={() => setProy(x.id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: 0, borderRadius: 999, padding: '4px 10px', fontSize: 12, cursor: 'pointer', background: x.id === proy ? 'var(--olive)' : 'var(--paper-2)', color: x.id === proy ? '#fff' : 'var(--ink-3)' }}>
              <Icon name={x.icon || 'home'} size={12} /> {x.nombre}
            </button>
          ))}
        </div>
      </div>

      {proy && <Composer proyectoId={proy} onGuardado={() => cargar(proy)} />}

      <div style={{ marginTop: 18, display: 'grid', gap: 10 }}>
        {anotaciones.length === 0 ? (
          <p style={{ color: 'var(--ink-4)', fontSize: 13 }}>Todavía no hay anotaciones. Escribí una nota o dibujá un bosquejo arriba.</p>
        ) : anotaciones.map((a) => {
          const trazos = a.bosquejos && a.bosquejos[0] ? a.bosquejos[0].trazos : null;
          return (
            <div key={a.id} className="card" style={{ padding: 14, display: 'grid', gap: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--olive-2)', background: 'var(--olive-tint)', padding: '2px 8px', borderRadius: 999 }}>{a.tipo}</span>
                <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-4)' }}>{(a.creado || '').slice(0, 10)}</span>
              </div>
              {a.texto && <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>{a.texto}</p>}
              {trazos && trazos.length > 0 && <BosquejoMini trazos={trazos} />}
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.CuadernoView = CuadernoView;
