/* global React, IconClose, IconExt, IconRefresh, IconBolt, IconMail, IconPhone, IconPin,
   IconClock, IconVideo, IconTag, IconGlobe, IconBuilding, IconCalendar, SourceBadge */
// Ficha del cliente que agendó (Calendly): contacto, cita, formulario,
// atribución (UTM), notas internas e historial.

function Drawer({ c, onClose, stages, closers, onChangeStage, onChangeCloser, onAddNote, onEditNote, onDeleteNote, onUpdateSale }) {
  const [tab, setTab] = React.useState("detalle");
  const { CALL_STATUS, SOURCES } = window.REVOLVR_DATA;
  const stage = stages.find((s) => s.id === c.stage);
  const closer = closers.find((x) => x.id === c.closerId);
  const st = CALL_STATUS[c.status] || {};
  const src = SOURCES[c.utm.source] || { label: c.utm.source, color: "#94a3b8" };
  const [noteDraft, setNoteDraft] = React.useState("");
  const [editingNote, setEditingNote] = React.useState(null);
  const [editDraft, setEditDraft] = React.useState("");

  const initials = c.name.split(" ").map((s) => s[0]).slice(0, 2).join("");
  const dateLong = c.scheduledAt instanceof Date
    ? c.scheduledAt.toLocaleDateString("es-ES", { weekday: "long", day: "numeric", month: "long" }) + " · " +
      c.scheduledAt.toLocaleTimeString("es-ES", { hour: "2-digit", minute: "2-digit", hour12: false })
    : "";

  const addNote = () => { const t = noteDraft.trim(); if (!t) return; onAddNote(c.id, t); setNoteDraft(""); };

  return (
    <>
      <div className="drawer-back" onClick={onClose}/>
      <div className="drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-head">
          <div className="rv-avatar lg" style={{ background: closer ? closer.color : "var(--accent)" }}>{initials}</div>
          <div className="who">
            <h2>{c.name}</h2>
            <div className="handle">{c.form.industria} · {c.location}</div>
          </div>
          <div className="actions">
            <select value={c.stage} onChange={(e) => onChangeStage(c.id, e.target.value)} className="crm-btn" style={{ fontFamily: "inherit", paddingRight: 22 }}>
              {stages.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
            </select>
            <button className="close-btn" onClick={onClose} title="Cerrar"><IconClose size={14}/></button>
          </div>
        </div>

        <div className="drawer-meta">
          <Field label="Estado de la cita">
            <span className="status-pill" style={{ "--st": st.color }}><span className="d"/>{st.label}</span>
          </Field>
          <Field label="Etapa">
            <span className="stage-dot" style={{ background: stage?.color, width: 8, height: 8, borderRadius: "50%", display: "inline-block" }}/>{stage?.label}
          </Field>
          <Field label="Closer">
            <select value={c.closerId} onChange={(e) => onChangeCloser(c.id, e.target.value)} className="mini-select">
              {closers.map((cl) => <option key={cl.id} value={cl.id}>{cl.name}</option>)}
            </select>
          </Field>
          <Field label="Fuente"><SourceBadge source={c.utm.source}/></Field>
        </div>

        <div className="drawer-body">
          <div className="drawer-tabs">
            <button className="drawer-tab" data-active={tab === "detalle"} onClick={() => setTab("detalle")}>Detalle</button>
            <button className="drawer-tab" data-active={tab === "notes"} onClick={() => setTab("notes")}>Notas <span className="pill">{c.notes.length}</span></button>
            <button className="drawer-tab" data-active={tab === "hist"} onClick={() => setTab("hist")}>Historial</button>
          </div>

          <div className="drawer-pane">
            {tab === "detalle" && <DetailPane c={c} dateLong={dateLong} onUpdateSale={onUpdateSale}/>}
            {tab === "notes" &&
              <div className="notes-pane">
                {c.notes.length === 0 &&
                  <div style={{ color: "var(--text-3)", fontSize: 12.5, padding: "8px 0 14px" }}>Sin notas. Visibles solo para el equipo.</div>}
                {c.notes.map((n, i) =>
                  <div className="note-item" key={i}>
                    <div className="note-h">
                      <span>{n.who} · {n.ts}</span>
                      <div className="note-actions">
                        <button className="note-action-btn" title="Editar"
                          onClick={() => { setEditingNote(i); setEditDraft(n.body); }}>✏️</button>
                        <button className="note-action-btn danger" title="Borrar"
                          onClick={() => { if (window.confirm("¿Borrar esta nota?")) onDeleteNote(c.id, i); }}>🗑</button>
                      </div>
                    </div>
                    {editingNote === i
                      ? <div className="note-edit-wrap">
                          <textarea className="note-input" value={editDraft}
                            onChange={(e) => setEditDraft(e.target.value)}
                            onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { onEditNote(c.id, i, editDraft.trim()); setEditingNote(null); }}}/>
                          <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                            <button className="crm-btn" data-variant="primary"
                              onClick={() => { onEditNote(c.id, i, editDraft.trim()); setEditingNote(null); }}>Guardar</button>
                            <button className="crm-btn" data-variant="ghost"
                              onClick={() => setEditingNote(null)}>Cancelar</button>
                          </div>
                        </div>
                      : <div className="note-body">{n.body}</div>}
                  </div>)}
                <textarea className="note-input" placeholder="Agregar nota interna (Cmd+Enter)" value={noteDraft}
                          onChange={(e) => setNoteDraft(e.target.value)}
                          onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") addNote(); }}/>
                <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
                  <button className="crm-btn" data-variant="primary" onClick={addNote} disabled={!noteDraft.trim()}>Guardar nota</button>
                </div>
              </div>}
            {tab === "hist" &&
              <div className="hist-list">
                {c.history.map((h, i) =>
                  <div className="hist-item" key={i}>
                    <div className="hist-dot" data-kind={h.kind}/>
                    <div className="hist-text">
                      <div><span className="e">{h.e}</span> {h.det && <span className="det">— {h.det}</span>}</div>
                      <div className="ts">{h.ts}</div>
                    </div>
                  </div>)}
                {c.history.length === 0 && <div className="empty">Sin eventos registrados</div>}
              </div>}
          </div>
        </div>
      </div>
    </>);
}

function DetailPane({ c, dateLong, onUpdateSale }) {
  const SOURCES = window.REVOLVR_DATA.SOURCES;
  const src = SOURCES[c.utm.source] || { label: c.utm.source };
  return (
    <div className="detail-pane">
      {/* Venta (solo cuando la llamada está cerrada ganada) */}
      {c.stage === "ganada" && <SaleSection c={c} onUpdateSale={onUpdateSale}/>}
      {/* Cita */}
      <section className="dp-section">
        <h4>Cita agendada</h4>
        <div className="dp-rows">
          <InfoRow icon={<IconCalendar size={14}/>} label="Fecha y hora" value={dateLong}/>
          <InfoRow icon={<IconClock size={14}/>} label="Tipo de evento" value={c.eventType}/>
          <InfoRow icon={<IconGlobe size={14}/>} label="Zona horaria" value={c.timezone}/>
          <InfoRow icon={<IconVideo size={14}/>} label="Reunión" value={<a href={c.meetingLink} target="_blank" rel="noreferrer" className="dp-link">Abrir enlace ↗</a>}/>
        </div>
        <button className="crm-btn" data-variant="primary" style={{ marginTop: 12, width: "100%", justifyContent: "center" }}>
          <IconVideo size={13}/> Unirse a la llamada
        </button>
      </section>

      {/* Contacto */}
      <section className="dp-section">
        <h4>Contacto</h4>
        <div className="dp-rows">
          <InfoRow icon={<IconMail size={14}/>} label="Correo" value={<a href={"mailto:" + c.email} className="dp-link">{c.email}</a>}/>
          <InfoRow icon={<IconPhone size={14}/>} label="Teléfono" value={<PhoneValue phone={c.phone}/>}/>
          <InfoRow icon={<IconPin size={14}/>} label="Ubicación" value={c.location}/>
        </div>
      </section>

      {/* Respuestas del formulario de Calendly */}
      <section className="dp-section">
        <h4>Respuestas del formulario</h4>
        <div className="dp-form">
          <FormCell icon={<IconBuilding size={14}/>} label="Industria" value={c.form.industria}/>
          <FormCell icon={<IconUserMini/>} label="Equipo" value={c.form.equipo}/>
          <FormCell icon={<IconMoney/>} label="Facturación" value={c.form.facturacion}/>
          <FormCell wide label="¿Qué quiere resolver?" value={c.form.objetivo}/>
        </div>
      </section>

      {/* Atribución / UTM */}
      <section className="dp-section">
        <h4>Atribución (UTM)</h4>
        <div className="dp-utm">
          <div className="utm-chip"><span className="k">source</span><span className="v" style={{ color: src.color || "var(--text)" }}>{c.utm.source}</span></div>
          <div className="utm-chip"><span className="k">medium</span><span className="v">{c.utm.medium}</span></div>
          <div className="utm-chip"><span className="k">campaign</span><span className="v">{c.utm.campaign}</span></div>
        </div>
      </section>
    </div>);
}

function SaleSection({ c, onUpdateSale }) {
  const base = c.sale || { programa: "", total: c.value || 0, tipo: "total", pagado: 0 };
  const [sale, setSale] = React.useState(base);
  const [dirty, setDirty] = React.useState(false);
  React.useEffect(() => { setSale(c.sale || base); setDirty(false); /* eslint-disable-next-line */ }, [c.id]);

  const set = (patch) => { setSale((s) => ({ ...s, ...patch })); setDirty(true); };
  const pagado = sale.tipo === "total" ? Number(sale.total || 0) : Number(sale.pagado || 0);
  const saldo = Math.max(0, Number(sale.total || 0) - pagado);
  const paid = saldo <= 0 && Number(sale.total) > 0;

  const save = () => {
    const clean = { programa: sale.programa.trim() || "Programa", total: Number(sale.total) || 0,
      tipo: sale.tipo, pagado: sale.tipo === "total" ? Number(sale.total) || 0 : Number(sale.pagado) || 0 };
    onUpdateSale(c.id, clean);
    setDirty(false);
  };

  return (
    <section className="dp-section sale-section">
      <h4>Venta <span className="pay-pill" data-paid={paid ? "true" : undefined}>{paid ? "Pagado" : "Saldo pendiente"}</span></h4>
      <div className="sale-form">
        <label className="sale-field wide">
          <span>Programa vendido</span>
          <input value={sale.programa} placeholder="Ej. Aceleradora REVOLVR" onChange={(e) => set({ programa: e.target.value })}/>
        </label>
        <label className="sale-field">
          <span>Total facturado</span>
          <div className="sale-money"><i>$</i><input type="number" min="0" step="100" value={sale.total} onChange={(e) => set({ total: e.target.value })}/></div>
        </label>
        <div className="sale-field">
          <span>Tipo de pago</span>
          <div className="sale-toggle">
            <button data-on={sale.tipo === "total" ? "true" : undefined} onClick={() => set({ tipo: "total" })}>Pago total</button>
            <button data-on={sale.tipo === "abono" ? "true" : undefined} onClick={() => set({ tipo: "abono" })}>Abono</button>
          </div>
        </div>
        {sale.tipo === "abono" &&
          <label className="sale-field">
            <span>Monto pagado</span>
            <div className="sale-money"><i>$</i><input type="number" min="0" step="100" value={sale.pagado} onChange={(e) => set({ pagado: e.target.value })}/></div>
          </label>}
        {sale.tipo === "abono" &&
          <div className="sale-field">
            <span>Saldo pendiente</span>
            <div className="sale-saldo" data-paid={paid ? "true" : undefined}>{"$" + saldo.toLocaleString("en-US")}</div>
          </div>}
      </div>
      <div className="sale-actions">
        {!paid && sale.tipo === "abono" && <button className="crm-btn" onClick={() => { set({ tipo: "total" }); }}>Marcar como pagado</button>}
        <button className="crm-btn" data-variant="primary" onClick={save} disabled={!dirty}>Guardar venta</button>
      </div>
    </section>);
}

function PhoneValue({ phone }) {
  const [copied, setCopied] = React.useState(false);
  const waUrl = "https://wa.me/" + phone.replace(/[^\d]/g, "");
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText(phone);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <span className="phone-value">
      <span className="phone-num" title="Seleccionable">{phone}</span>
      <button className="phone-copy" onClick={copy} title="Copiar número">{copied ? "¡Copiado!" : "Copiar"}</button>
      <a className="phone-wa" href={waUrl} target="_blank" rel="noopener noreferrer"
         onClick={(e) => { e.preventDefault(); window.open(waUrl, "_blank", "noopener,noreferrer"); }}>WhatsApp ↗</a>
    </span>);
}

function InfoRow({ icon, label, value }) {
  return (
    <div className="info-row">
      <span className="ir-ic">{icon}</span>
      <span className="ir-label">{label}</span>
      <span className="ir-value">{value}</span>
    </div>);
}

function FormCell({ icon, label, value, wide }) {
  return (
    <div className={"form-cell" + (wide ? " wide" : "")}>
      <div className="fc-label">{icon && <span className="fc-ic">{icon}</span>}{label}</div>
      <div className="fc-value">{value}</div>
    </div>);
}

const IconUserMini = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="3.4"/><path d="M5 20a7 7 0 0 1 14 0"/></svg>
);
const IconMoney = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v18M16 7.5c0-1.4-1.8-2.5-4-2.5s-4 1-4 2.4c0 3.3 8 1.8 8 5.1 0 1.5-1.8 2.5-4 2.5s-4-1-4-2.5"/></svg>
);

function Field({ label, children }) {
  return (
    <div className="field">
      <div className="lbl">{label}</div>
      <div className="val">{children}</div>
    </div>);
}

Object.assign(window, { Drawer });
