/* global React, Icon, SOPAI, SOPStore */
/* Editor — left panel. Inputs that drive the doc state. */

const { useState: useStateE, useRef: useRefE, useCallback: useCallbackE } = React;
const { uid: uidE } = window.SOPStore;

/* ============ Small reusable bits ============ */

function Field({ label, hint, children }) {
  return (
    <div className="field">
      {label && <label className="field__label">{label}</label>}
      {children}
      {hint && <div className="field__hint">{hint}</div>}
    </div>
  );
}

function SectionShell({ num, title, icon, defaultOpen = true, children }) {
  const [open, setOpen] = useStateE(defaultOpen);
  return (
    <div className={`editor__section ${open ? "" : "editor__section--collapsed"}`}>
      <div className="editor__section-head" onClick={() => setOpen(o => !o)}>
        {num != null && <span className="editor__section-num">{num}</span>}
        {icon && !num && <span className="editor__section-num" style={{ background: "transparent", color: "var(--teal-500)", border: "1px solid var(--line-2)" }}>{icon}</span>}
        <span className="editor__section-title">{title}</span>
        <span className="editor__section-spacer" />
        <span className="editor__section-chev"><Icon name="chevronDown" size={18} /></span>
      </div>
      <div className="editor__section-body">{children}</div>
    </div>
  );
}

/* ============ EDITOR ROOT ============ */

function Editor({ doc, onChange, onToast }) {
  // --- helpers
  const upd = (patch) => onChange({ ...doc, ...patch, updatedAt: Date.now() });

  /* ===== AI structurer ===== */
  const [rawNotes, setRawNotes] = useStateE("");
  const [aiBusy, setAiBusy] = useStateE(false);
  const [aiError, setAiError] = useStateE("");
  // Imágenes adjuntas al prompt (solo Codex las procesa).
  const [aiImages, setAiImages] = useStateE([]);
  const aiFileInputRef = useRefE(null);
  const AI_MAX_IMGS = 6;
  const AI_MAX_BYTES = 8 * 1024 * 1024;
  const readAsDataUrl = (file) => new Promise((res, rej) => {
    const r = new FileReader();
    r.onload = () => res({
      id: crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`,
      name: file.name, size: file.size, dataUrl: r.result,
    });
    r.onerror = () => rej(new Error("No pude leer la imagen"));
    r.readAsDataURL(file);
  });
  const addAIImages = async (filesLike) => {
    if (!filesLike || !filesLike.length) return;
    const files = Array.from(filesLike).filter(f => f.type && f.type.startsWith("image/"));
    if (!files.length) { setAiError("Solo imágenes (PNG, JPG, etc)."); return; }
    if (files.some(f => f.size > AI_MAX_BYTES)) { setAiError("Hay una imagen > 8 MB. Reducila antes."); return; }
    if (aiImages.length + files.length > AI_MAX_IMGS) {
      setAiError(`Máximo ${AI_MAX_IMGS} imágenes por prompt.`); return;
    }
    try {
      const descs = await Promise.all(files.map(readAsDataUrl));
      setAiImages(prev => [...prev, ...descs]);
      setAiError("");
    } catch (e) {
      setAiError(e.message || "Error leyendo imagen");
    }
  };
  const removeAIImage = (id) => setAiImages(prev => prev.filter(im => im.id !== id));

  const runAI = async () => {
    setAiError("");
    if (!rawNotes.trim() && aiImages.length === 0) {
      setAiError("Pega notas o adjuntá capturas."); return;
    }
    if (aiImages.length > 0 && (window.__SOP_PROVIDER || "codex") !== "codex") {
      setAiError("Para procesar imágenes cambiá a Codex en el toggle del header."); return;
    }
    setAiBusy(true);
    try {
      const imgUrls = aiImages.map(im => im.dataUrl);
      const text = rawNotes || "Genera un SOP a partir de las capturas adjuntas.";
      const structured = await window.SOPAI.structure(text, doc, imgUrls);
      onChange(structured);
      onToast && onToast("Estructurado por IA ✓");
      setRawNotes("");
      setAiImages([]);
    } catch (e) {
      setAiError(e.message || "Algo salió mal.");
    } finally {
      setAiBusy(false);
    }
  };

  /* ===== Roles / Resources / Definitions / References — generic list helpers ===== */
  const addRow = (key) => upd({ [key]: [...(doc[key] || []), { id: uidE(), name: "", desc: "", term: "", meaning: "" }] });
  const updRow = (key, id, patch) => upd({ [key]: doc[key].map(r => r.id === id ? { ...r, ...patch } : r) });
  const delRow = (key, id) => upd({ [key]: doc[key].filter(r => r.id !== id) });

  /* ===== Flow ===== */
  // Guards defensivos: la IA puede devolver doc sin alguna key — sin guard
  // el editor crasheaba (.map de undefined).
  const updFlow = (i, v) => upd({ flow: (doc.flow || []).map((s, idx) => idx === i ? v : s) });
  const addFlow = () => upd({ flow: [...(doc.flow || []), ""] });
  const delFlow = (i) => upd({ flow: (doc.flow || []).filter((_, idx) => idx !== i) });

  /* ===== Phases ===== */
  const updPhase = (id, patch) => upd({ phases: (doc.phases || []).map(p => p.id === id ? { ...p, ...patch } : p) });
  const addPhase = () => {
    const n = (doc.phases?.length || 0) + 1;
    upd({ phases: [...(doc.phases || []), { id: uidE(), num: n, title: `Fase ${n}`, steps: [{ id: uidE(), num: `${n}.1`, title: "", body: "", time: "", done: false, image: "", substeps: [] }] }] });
  };
  const delPhase = (id) => upd({ phases: (doc.phases || []).filter(p => p.id !== id) });

  /* ===== Steps within a phase ===== */
  const updStep = (phaseId, stepId, patch) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    if (!ph) return;
    updPhase(phaseId, {
      steps: (ph.steps || []).map(s => s.id === stepId ? { ...s, ...patch } : s),
    });
  };
  const addStep = (phaseId) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    if (!ph) return;
    const next = (ph.steps?.length || 0) + 1;
    updPhase(phaseId, { steps: [...(ph.steps || []), { id: uidE(), num: `${ph.num}.${next}`, title: "", body: "", time: "", done: false, image: "", substeps: [] }] });
  };
  const delStep = (phaseId, stepId) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    if (!ph) return;
    updPhase(phaseId, { steps: (ph.steps || []).filter(s => s.id !== stepId) });
  };

  /* ===== Substeps ===== */
  const addSubstep = (phaseId, stepId) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    const st = ph?.steps?.find(s => s.id === stepId);
    if (!st) return;
    const next = String.fromCharCode(97 + (st.substeps?.length || 0));
    updStep(phaseId, stepId, { substeps: [...(st.substeps || []), { id: uidE(), num: next, text: "" }] });
  };
  const updSubstep = (phaseId, stepId, ssId, patch) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    const st = ph?.steps?.find(s => s.id === stepId);
    if (!st) return;
    updStep(phaseId, stepId, { substeps: (st.substeps || []).map(ss => ss.id === ssId ? { ...ss, ...patch } : ss) });
  };
  const delSubstep = (phaseId, stepId, ssId) => {
    const ph = (doc.phases || []).find(p => p.id === phaseId);
    const st = ph?.steps?.find(s => s.id === stepId);
    if (!st) return;
    updStep(phaseId, stepId, { substeps: (st.substeps || []).filter(ss => ss.id !== ssId) });
  };

  /* ===== Image upload (per step) ===== */
  const onImageUpload = (phaseId, stepId, file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => updStep(phaseId, stepId, { image: e.target.result });
    reader.readAsDataURL(file);
  };

  /* ============ RENDER ============ */
  return (
    <div className="editor">
      <div className="editor__intro">
        <h2 className="editor__intro-title">Editor del SOP</h2>
        <p className="editor__intro-sub">Rellena cada sección. El documento de la derecha se actualiza en vivo. ¿Tienes notas en bruto? Pega aquí abajo y pulsa <strong>Estructurar con IA</strong>.</p>
      </div>

      {/* --- AI bar --- */}
      <SectionShell title="Estructurar con IA" icon={<Icon name="sparkles" size={13} />} defaultOpen={true}>
        <Field hint="Pega o dicta notas en cualquier orden — pasos sueltos, ideas, copy de Slack, etc. La IA detectará secciones, fases y pasos.">
          <div className="textarea-with-mic">
            <textarea
              className="textarea"
              placeholder="Pega o dicta aquí tus notas en bruto…"
              value={rawNotes}
              onChange={(e) => setRawNotes(e.target.value)}
              style={{ minHeight: 100 }}
            />
            <window.MicButton
              size={32}
              onTranscript={(t) => setRawNotes(prev => (prev + (prev && !/\s$/.test(prev) ? " " : "") + t).trim() + " ")}
            />
          </div>
        </Field>
        {/* Thumbnails de las imágenes adjuntas */}
        {aiImages.length > 0 && (
          <div className="simple-images" style={{ marginTop: 4, marginBottom: 4 }}>
            {aiImages.map(im => (
              <div key={im.id} className="simple-images__thumb" title={`${im.name} · ${(im.size/1024).toFixed(0)} KB`}>
                <img src={im.dataUrl} alt={im.name} />
                <button
                  className="simple-images__remove"
                  onClick={() => removeAIImage(im.id)}
                  title="Quitar"
                  disabled={aiBusy}
                >
                  <Icon name="x" size={11} />
                </button>
              </div>
            ))}
          </div>
        )}
        <input
          ref={aiFileInputRef}
          type="file"
          accept="image/*"
          multiple
          style={{ display: "none" }}
          onChange={(e) => { addAIImages(e.target.files); e.target.value = ""; }}
        />
        <div className="ai-bar">
          <span className="ai-bar__icon"><Icon name="sparkles" size={14} /></span>
          <span className="ai-bar__text">{aiError ? <span style={{ color: "var(--status-red)" }}>{aiError}</span> : "La IA reemplazará el contenido actual con la versión estructurada."}</span>
          <button
            className="btn simple-input__attach"
            onClick={() => aiFileInputRef.current && aiFileInputRef.current.click()}
            disabled={aiBusy || aiImages.length >= AI_MAX_IMGS}
            title="Adjuntar capturas (máx. 6). Codex las usa para detectar pasos visibles."
            style={{ marginRight: 6 }}
          >
            <Icon name="image" size={12} /> Imagen
            {aiImages.length > 0 && <span className="simple-input__attach-count">{aiImages.length}</span>}
          </button>
          <button className="ai-bar__btn" onClick={runAI} disabled={aiBusy}>
            {aiBusy ? <span className="spinner" /> : <Icon name="sparkles" size={12} />}
            {aiBusy ? "Procesando…" : "Estructurar"}
          </button>
        </div>
      </SectionShell>

      {/* --- 0. Metadata --- */}
      <SectionShell num="·" title="Identificación" defaultOpen={true}>
        <Field label="Título del SOP" hint="Sentence case. Conciso y orientado a la acción.">
          <input className="input" value={doc.title} onChange={(e) => upd({ title: e.target.value })} placeholder="Ej: Subida de Plantillas de Email a GHL con IA" />
        </Field>
        <div className="field--row">
          <Field label="Versión">
            <input className="input" value={doc.version} onChange={(e) => upd({ version: e.target.value })} placeholder="1.0" />
          </Field>
          <Field label="Fecha">
            <input type="date" className="input" value={doc.date} onChange={(e) => upd({ date: e.target.value })} />
          </Field>
        </div>
      </SectionShell>

      {/* --- Intro / contexto --- */}
      <SectionShell num="1" title="Contexto y resumen" defaultOpen={true}>
        <Field label="Introducción (opcional)" hint='Usa **doble asterisco** para negrita y "• " al inicio de línea para bullets.'>
          <textarea className="textarea" rows={5} value={doc.intro} onChange={(e) => upd({ intro: e.target.value })}
            placeholder="A continuación se detalla el proceso para…" />
        </Field>
        <Field label="Objetivo">
          <textarea className="textarea" rows={2} value={doc.objective} onChange={(e) => upd({ objective: e.target.value })}
            placeholder="La finalidad específica del proceso." />
        </Field>
        <Field label="Alcance">
          <textarea className="textarea" rows={2} value={doc.scope} onChange={(e) => upd({ scope: e.target.value })}
            placeholder="A qué situaciones o personas aplica este SOP." />
        </Field>
        <Field label="Resumen del flujo" hint="Lista de pasos cortos, uno por línea. Se renderizan con flechas entre ellos.">
          <div className="inline-list">
            {(doc.flow || []).map((step, i) => (
              <div key={i} className="inline-row" style={{ gridTemplateColumns: "28px 1fr 28px" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: "var(--teal-500)", textAlign: "center", paddingTop: 9 }}>{i + 1}.</span>
                <input className="input" value={step} onChange={(e) => updFlow(i, e.target.value)} placeholder={`Paso del flujo ${i + 1}…`} />
                <button className="inline-row__remove" onClick={() => delFlow(i)} title="Eliminar"><Icon name="x" size={13} /></button>
              </div>
            ))}
            <button className="add-row" onClick={addFlow}><Icon name="plus" size={13} /> Añadir paso del flujo</button>
          </div>
        </Field>
      </SectionShell>

      {/* --- 2. Roles --- */}
      <SectionShell num="2" title="Roles y responsabilidades" defaultOpen={false}>
        <div className="inline-list">
          {(doc.roles || []).map(r => (
            <div key={r.id} className="inline-row">
              <input className="input" value={r.name} onChange={(e) => updRow("roles", r.id, { name: e.target.value })} placeholder="Rol (ej: Especialista en Automatización)" />
              <input className="input" value={r.desc} onChange={(e) => updRow("roles", r.id, { desc: e.target.value })} placeholder="Tareas / responsabilidades" />
              <button className="inline-row__remove" onClick={() => delRow("roles", r.id)} title="Eliminar"><Icon name="x" size={13} /></button>
            </div>
          ))}
          <button className="add-row" onClick={() => addRow("roles")}><Icon name="plus" size={13} /> Añadir rol</button>
        </div>
      </SectionShell>

      {/* --- 3. Resources --- */}
      <SectionShell num="3" title="Recursos y herramientas" defaultOpen={false}>
        <div className="inline-list">
          {(doc.resources || []).map(r => (
            <div key={r.id} className="inline-row">
              <input className="input" value={r.name} onChange={(e) => updRow("resources", r.id, { name: e.target.value })} placeholder="Recurso (ej: GoHighLevel)" />
              <input className="input" value={r.desc} onChange={(e) => updRow("resources", r.id, { desc: e.target.value })} placeholder="Para qué se usa" />
              <button className="inline-row__remove" onClick={() => delRow("resources", r.id)} title="Eliminar"><Icon name="x" size={13} /></button>
            </div>
          ))}
          <button className="add-row" onClick={() => addRow("resources")}><Icon name="plus" size={13} /> Añadir recurso</button>
        </div>
      </SectionShell>

      {/* --- 4. Procedure --- */}
      <SectionShell num="4" title="Procedimiento paso a paso" defaultOpen={true}>
        {(doc.phases || []).map(phase => (
          <div key={phase.id} className="phase">
            <div className="phase__head">
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, color: "var(--cream-100)", background: "var(--teal-500)", padding: "3px 8px", borderRadius: 999, letterSpacing: "0.05em", textTransform: "uppercase" }}>
                Fase {phase.num}
              </span>
              <input className="phase__title" value={phase.title} onChange={(e) => updPhase(phase.id, { title: e.target.value })} placeholder="Título de la fase" />
              <button className="inline-row__remove" onClick={() => delPhase(phase.id)} title="Eliminar fase"><Icon name="trash" size={13} /></button>
            </div>
            {(phase.steps || []).map(step => (
              <div key={step.id} className="step">
                <div className="step__head">
                  <input className="input step__num-input" value={step.num} onChange={(e) => updStep(phase.id, step.id, { num: e.target.value })} />
                  <input className="input step__title-input" value={step.title} onChange={(e) => updStep(phase.id, step.id, { title: e.target.value })} placeholder="Título del paso" />
                  <button className="inline-row__remove" onClick={() => delStep(phase.id, step.id)} title="Eliminar paso"><Icon name="x" size={13} /></button>
                </div>
                <div className="step__body">
                  <textarea className="textarea" rows={2} value={step.body} onChange={(e) => updStep(phase.id, step.id, { body: e.target.value })} placeholder="Detalle del paso…" />
                  {/* Substeps */}
                  {(step.substeps || []).length > 0 && (
                    <div className="step__substeps">
                      {step.substeps.map(ss => (
                        <div key={ss.id} className="step__substep-row">
                          <input className="input step__num-input" style={{ fontSize: 11, padding: "5px 6px" }} value={ss.num} onChange={(e) => updSubstep(phase.id, step.id, ss.id, { num: e.target.value })} />
                          <input className="input" style={{ fontSize: 12.5, padding: "6px 9px" }} value={ss.text} onChange={(e) => updSubstep(phase.id, step.id, ss.id, { text: e.target.value })} placeholder="Sub-paso…" />
                          <button className="inline-row__remove" onClick={() => delSubstep(phase.id, step.id, ss.id)} title="Eliminar"><Icon name="x" size={13} /></button>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="step__meta">
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--fg-3)", fontSize: 11 }}>
                      <Icon name="clock" size={12} />
                    </span>
                    <input className="input step__meta-input" value={step.time} onChange={(e) => updStep(phase.id, step.id, { time: e.target.value })} placeholder="Tiempo (ej: 10 min)" />
                    <label className="step__check">
                      <input type="checkbox" checked={!!step.done} onChange={(e) => updStep(phase.id, step.id, { done: e.target.checked })} /> Completado
                    </label>
                    <span style={{ flex: 1 }} />
                    <button className="btn btn--sm btn--ghost" onClick={() => addSubstep(phase.id, step.id)}>
                      <Icon name="plus" size={11} /> Sub-paso
                    </button>
                    <label className="btn btn--sm btn--ghost" style={{ cursor: "pointer" }}>
                      <Icon name="image" size={11} /> Imagen
                      <input type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => onImageUpload(phase.id, step.id, e.target.files[0])} />
                    </label>
                  </div>
                  {step.image && (
                    <div style={{ position: "relative", marginTop: 6, width: "fit-content" }}>
                      <img src={step.image} className="step__img-preview" alt="" />
                      <button onClick={() => updStep(phase.id, step.id, { image: "" })}
                        style={{ position: "absolute", top: 4, right: 4, background: "rgba(0,0,0,0.55)", color: "#fff", border: "none", borderRadius: 999, width: 22, height: 22, display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
                        <Icon name="x" size={12} />
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
            <button className="add-row" onClick={() => addStep(phase.id)}><Icon name="plus" size={13} /> Añadir paso a esta fase</button>
          </div>
        ))}
        <button className="add-row" style={{ marginTop: 4 }} onClick={addPhase}><Icon name="plus" size={13} /> Añadir nueva fase</button>
      </SectionShell>

      {/* --- 5. Definitions --- */}
      <SectionShell num="5" title="Definiciones" defaultOpen={false}>
        <div className="inline-list">
          {(doc.definitions || []).map(d => (
            <div key={d.id} className="inline-row">
              <input className="input" value={d.term} onChange={(e) => updRow("definitions", d.id, { term: e.target.value })} placeholder="Término (ej: GHL)" />
              <input className="input" value={d.meaning} onChange={(e) => updRow("definitions", d.id, { meaning: e.target.value })} placeholder="Definición" />
              <button className="inline-row__remove" onClick={() => delRow("definitions", d.id)} title="Eliminar"><Icon name="x" size={13} /></button>
            </div>
          ))}
          <button className="add-row" onClick={() => addRow("definitions")}><Icon name="plus" size={13} /> Añadir definición</button>
        </div>
      </SectionShell>

      {/* --- 6. References --- */}
      <SectionShell num="6" title="Referencias" defaultOpen={false}>
        <div className="inline-list">
          {(doc.references || []).map(r => (
            <div key={r.id} className="inline-row">
              <input className="input" value={r.term} onChange={(e) => updRow("references", r.id, { term: e.target.value })} placeholder="Documento / política" />
              <input className="input" value={r.meaning} onChange={(e) => updRow("references", r.id, { meaning: e.target.value })} placeholder="Descripción o enlace" />
              <button className="inline-row__remove" onClick={() => delRow("references", r.id)} title="Eliminar"><Icon name="x" size={13} /></button>
            </div>
          ))}
          <button className="add-row" onClick={() => addRow("references")}><Icon name="plus" size={13} /> Añadir referencia</button>
        </div>
      </SectionShell>
    </div>
  );
}

window.Editor = Editor;
