// =========================================================================
// CLIENT DETAIL — Perfil completo del cliente
// =========================================================================

const ClientDetail = ({ clientId, onBack }) => {
  const { Icons, DATA, Card } = window;
  const c = DATA.CLIENTS.find(x => x.id === clientId);
  const [tab, setTab] = React.useState("resumen");
  const [subiendoDoc, setSubiendoDoc] = React.useState(false);
  const [, setRefreshDocs] = React.useState(0);
  const [errDoc, setErrDoc] = React.useState("");
  const descargar = async (d) => {
    setErrDoc("");
    try { await window.RevinSupabase.descargarDocumento(d); }
    catch (e) { setErrDoc((e && e.message) || "No se ha podido abrir el documento."); }
  };
  // OJO CON LA RUTA: en el shape de CLIENTS el uuid va DENTRO (`c.supabase.id`),
  // no al nivel superior como en TEAM. Es la misma trampa del bug estado/activo.
  const cUid = (c && c.supabase && c.supabase.id) || null;
  const docsCliente = (DATA.DOCS_BY_CLIENT && cUid && DATA.DOCS_BY_CLIENT[cUid]) || [];
  const trasSubirDoc = async () => {
    try {
      window.DATA = await window.RevinSupabase.loadDataFromSupabase();
      setRefreshDocs(r => r + 1);
    } catch (e) { console.error(e); }
  };

  if (!c) {
    return (
      <div className="empty">
        <div className="icon-wrap"><Icons.User/></div>
        Cliente no encontrado.
        <div style={{marginTop: 12}}>
          <button className="btn secondary" onClick={onBack}><Icons.ChevronLeft/> Volver</button>
        </div>
      </div>
    );
  }

  const sb = c.supabase || {};
  const ui = window.RevinSupabase?.ui || {};
  const isProveedor = c.typeKey === "proveedor";
  const isBuscador = ["comprador", "inversor", "arrendatario"].includes(c.typeKey);
  const isPropietario = c.typeKey === "propietario" || c.typeKey === "vendedor";

  // Valores derivados null-safe (algunos clientes importados tienen tipo/nombre vacíos).
  const safeUpper = (v) => (v == null ? "" : String(v).toUpperCase());
  const typeLabel = (ui.clienteType ? ui.clienteType(c.typeKey) : c.type) || "Sin tipo";
  const initials = (c.displayName || c.name || "").split(" ").map(p => p[0]).filter(Boolean).slice(0, 2).join("").toUpperCase() || "?";

  const waLink = () => {
    if (!c.phone) return "#";
    const clean = c.phone.replace(/[^\d+]/g, "");
    const firstName = (c.name || "").split(" ")[0] || "";
    return `https://wa.me/${clean.replace("+", "")}?text=${encodeURIComponent(`Hola ${firstName}, te escribo desde REVIN...`)}`;
  };

  // Tone according to tipo
  const toneByType = (t) => ({
    proveedor: "warning", inversor: "warning", comprador: "info",
    propietario: "brand", vendedor: "neutral", arquitecto: "info",
    notaria: "neutral", gestoria: "neutral", colaborador: "brand",
    inmobiliaria: "brand", organismo_publico: "neutral", consultora: "info",
    arrendatario: "info",
  }[t] || "neutral");

  // Días desde último contacto
  const daysSinceContact = sb.responsable_raw && c.lastContactRaw
    ? Math.floor((Date.now() - new Date(c.lastContactRaw).getTime()) / 86400000)
    : null;

  // KV item
  const KV = ({ lbl, value, mono }) => (
    <div className="kv">
      <div className="kv-lbl">{lbl}</div>
      <div className="kv-val" style={mono ? {fontFamily: "var(--font-mono)", fontSize: 12} : {}}>
        {value || <span style={{color: "var(--fg-4)", fontWeight: 400}}>—</span>}
      </div>
    </div>
  );

  return (
    <>
      {/* Back + actions */}
      <div className="page-h">
        <div>
          <button className="btn ghost xs" onClick={onBack} style={{paddingLeft: 0, marginBottom: 6}}>
            <Icons.ChevronLeft/> Volver a {isProveedor ? "Proveedores" : "Clientes"}
          </button>
        </div>
        <div className="actions">
          {c.phone && <a className="btn secondary" href={`tel:${c.phone.replace(/\s/g, "")}`}><Icons.Phone/> Llamar</a>}
          {c.email && <a className="btn secondary" href={`mailto:${c.email}`}><Icons.Mail/> Email</a>}
          {c.phone && <a className="btn dark" style={{background: "#25D366", borderColor: "#25D366"}} href={waLink()} target="_blank"><Icons.Whatsapp/> WhatsApp</a>}
          <button className="btn primary"><Icons.Plus/> Asociar a proyecto</button>
        </div>
      </div>

      {/* Hero */}
      <div className="card" style={{marginBottom: 24, padding: 0, overflow: "hidden"}}>
        <div style={{padding: "24px 28px", display: "flex", gap: 20, alignItems: "flex-start", borderBottom: "1px solid var(--border-1)", background: "var(--bg-surface)"}}>
          <div className="sb-avatar" style={{
            width: 72, height: 72, fontSize: 24, flexShrink: 0,
            background: c.cooling ? "var(--revin-red)" : (isProveedor ? "var(--warning)" : "var(--revin-black)"),
          }}>
            {initials}
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div className="eyebrow red" style={{marginBottom: 4}}>
              {typeLabel} · {sb.figura_legal && ui.figura ? ui.figura(sb.figura_legal) : ""}
            </div>
            <h1 style={{margin: 0, fontSize: 32, letterSpacing: ".02em"}}>{safeUpper(c.displayName || c.name) || "—"}</h1>
            {/* Desambiguador (54_). Debajo del nombre y en tono apagado: aclara
                de quién hablamos sin competir con el titular ni ensuciar el
                nombre, que es señal de dedupe. */}
            {c.alias && (
              <div style={{fontSize: 14, color: "var(--fg-3)", marginTop: 2}}>{c.alias}</div>
            )}
            <div style={{display: "flex", gap: 8, marginTop: 10, alignItems: "center", flexWrap: "wrap"}}>
              <Pill tone={toneByType(c.typeKey)}>{safeUpper(typeLabel)}</Pill>
              {sb.tipo_proveedor && <Pill tone="warning">{ui.provType ? ui.provType(sb.tipo_proveedor).toUpperCase() : sb.tipo_proveedor.toUpperCase()}</Pill>}
              {sb.estado && <Pill tone={c.cooling ? "danger" : sb.estado === "cierre" ? "success" : "info"}>{ui.estado ? ui.estado(sb.estado).toUpperCase() : sb.estado.toUpperCase()}</Pill>}
              {c.cooling && <Pill tone="danger"><Icons.Flame size={10}/> EN RIESGO</Pill>}
              {sb.origen || c.originKey ? <Pill tone="neutral">{ui.origin ? ui.origin(c.originKey) : c.origin}</Pill> : null}
            </div>
          </div>
          <div style={{textAlign: "right", flexShrink: 0}}>
            <div className="kv-lbl">Responsable</div>
            <div style={{fontSize: 13, fontWeight: 600, marginTop: 4}}>{sb.responsable_raw || <span style={{color: "var(--fg-4)"}}>Sin asignar</span>}</div>
            {sb.entrada_al_pipeline && (
              <>
                <div className="kv-lbl" style={{marginTop: 14}}>En pipeline desde</div>
                <div style={{fontSize: 13, marginTop: 4}}>
                  {new Date(sb.entrada_al_pipeline).toLocaleDateString("es-ES", { day: "2-digit", month: "short", year: "numeric" })}
                </div>
                {sb.dias_en_pipeline != null && (
                  <div style={{fontSize: 11, color: "var(--fg-3)", marginTop: 2}}>{sb.dias_en_pipeline} días</div>
                )}
              </>
            )}
          </div>
        </div>

        {/* Quick-stats strip */}
        <div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "0", background: "var(--bg-inset)"}}>
          {[
            { lbl: "Teléfono", val: c.phone, icon: Icons.Phone },
            { lbl: "Email", val: c.email, icon: Icons.Mail, mono: true },
            { lbl: "Último contacto", val: c.lastContact !== "—" ? c.lastContact : null, icon: Icons.Clock, urgent: daysSinceContact && daysSinceContact > 14 },
            { lbl: "Próximo seguimiento", val: sb.proximo_seguimiento ? new Date(sb.proximo_seguimiento).toLocaleDateString("es-ES", { day: "2-digit", month: "short", year: "numeric" }) : null, icon: Icons.Calendar },
          ].map((s, i) => (
            <div key={i} style={{padding: "14px 18px", borderRight: i < 3 ? "1px solid var(--border-1)" : "none"}}>
              <div className="kv-lbl" style={{display: "flex", alignItems: "center", gap: 6}}>
                <s.icon size={11}/>{s.lbl}
              </div>
              <div style={{fontSize: 13, fontWeight: 600, marginTop: 4, color: s.urgent ? "var(--revin-red)" : "var(--fg-1)", fontFamily: s.mono ? "var(--font-mono)" : "inherit"}}>
                {s.val || <span style={{color: "var(--fg-4)", fontWeight: 400}}>—</span>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div className="adm-tabs">
        <button className={"adm-tab" + (tab === "resumen" ? " active" : "")} onClick={() => setTab("resumen")}>Resumen</button>
        <button className={"adm-tab" + (tab === "datos" ? " active" : "")} onClick={() => setTab("datos")}>Datos completos</button>
        <button className={"adm-tab" + (tab === "proyectos" ? " active" : "")} onClick={() => setTab("proyectos")}>Proyectos</button>
        <button className={"adm-tab" + (tab === "documentos" ? " active" : "")} onClick={() => setTab("documentos")}>Documentos</button>
        <button className={"adm-tab" + (tab === "historial" ? " active" : "")} onClick={() => setTab("historial")}>Historial</button>
      </div>

      {tab === "resumen" && (
        <div style={{display: "grid", gridTemplateColumns: "2fr 1fr", gap: 20}}>
          <div style={{display: "flex", flexDirection: "column", gap: 20}}>
            {/* Contacto */}
            <Card title="Datos de contacto">
              <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16}}>
                <KV lbl="Teléfono" value={c.phone}/>
                <KV lbl="Email" value={c.email} mono/>
                <KV lbl="DNI / CIF" value={sb.dni_cif} mono/>
                <KV lbl="Figura legal" value={sb.figura_legal ? (ui.figura ? ui.figura(sb.figura_legal) : sb.figura_legal) : null}/>
                <KV lbl="Dirección" value={sb.direccion}/>
                <KV lbl="Código postal" value={sb.cp}/>
                <KV lbl="RRSS" value={sb.rrss} mono/>
                <KV lbl="Origen" value={ui.origin ? ui.origin(c.originKey) : c.origin}/>
              </div>
            </Card>

            {/* Búsqueda activa — solo para compradores/inversores/arrendatarios */}
            {isBuscador && (
              <Card title={isProveedor ? "Servicio que presta" : "Búsqueda activa"}>
                <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16}}>
                  <KV lbl="Motivación" value={sb.motivacion ? (ui.motivacion ? ui.motivacion(sb.motivacion) : sb.motivacion) : null}/>
                  <KV lbl="Tipo de inmueble" value={sb.tipo_inmueble_interes ? sb.tipo_inmueble_interes.toUpperCase() : null}/>
                  <KV lbl="Presupuesto mínimo" value={c.budget > 0 ? window.fmtEUR(c.budget) : null}/>
                  <KV lbl="Presupuesto máximo" value={c.budgetMax > 0 ? window.fmtEUR(c.budgetMax) : null}/>
                  <div style={{gridColumn: "1 / -1"}}>
                    <div className="kv-lbl">Zona de interés</div>
                    <div className="kv-val" style={{marginTop: 4}}>{c.zone || <span style={{color: "var(--fg-4)"}}>—</span>}</div>
                  </div>
                  <div style={{gridColumn: "1 / -1"}}>
                    <div className="kv-lbl">Requisitos</div>
                    <div className="kv-val" style={{marginTop: 4, fontWeight: 400, lineHeight: 1.5}}>{c.req || <span style={{color: "var(--fg-4)"}}>—</span>}</div>
                  </div>
                  <KV lbl="Financiación" value={c.financing && c.financing !== "—" ? c.financing : null}/>
                </div>
              </Card>
            )}

            {/* Si es proveedor, su servicio */}
            {isProveedor && (
              <Card title="Servicio que presta">
                <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16}}>
                  <KV lbl="Especialidad" value={sb.tipo_proveedor ? (ui.provType ? ui.provType(sb.tipo_proveedor) : sb.tipo_proveedor) : null}/>
                  <KV lbl="Zona de actuación" value={c.zone}/>
                  <div style={{gridColumn: "1 / -1"}}>
                    <div className="kv-lbl">Notas sobre el servicio</div>
                    <div className="kv-val" style={{marginTop: 4, fontWeight: 400, lineHeight: 1.5}}>{c.req || sb.notas_privadas || <span style={{color: "var(--fg-4)"}}>—</span>}</div>
                  </div>
                </div>
              </Card>
            )}

            {/* Si es propietario / vendedor */}
            {isPropietario && (
              <Card title="Inmueble en cartera">
                <div style={{display: "flex", flexDirection: "column", gap: 12, padding: 4}}>
                  <div style={{padding: 12, background: "var(--bg-inset)", borderRadius: 4, fontSize: 13, color: "var(--fg-2)"}}>
                    <Icons.Info size={12} style={{display: "inline", verticalAlign: "middle", marginRight: 6}}/>
                    Cuando importemos los inmuebles desde Notion, aquí aparecerá automáticamente el que vincula con este propietario.
                  </div>
                </div>
              </Card>
            )}

            {/* Notas */}
            {sb.notas_privadas && (
              <Card title="Notas privadas">
                <div style={{fontSize: 13, color: "var(--fg-1)", lineHeight: 1.6, whiteSpace: "pre-wrap"}}>{sb.notas_privadas}</div>
              </Card>
            )}
          </div>

          {/* Aside derecha */}
          <div style={{display: "flex", flexDirection: "column", gap: 20}}>
            {/* Próximas acciones */}
            <Card title="Próximas acciones">
              {sb.proximo_seguimiento ? (
                <div style={{display: "flex", gap: 10, alignItems: "flex-start", padding: 4}}>
                  <div style={{width: 32, height: 32, borderRadius: 4, background: "var(--red-50)", border: "1px solid var(--red-200)", color: "var(--revin-red)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0}}>
                    <Icons.Calendar size={14}/>
                  </div>
                  <div style={{flex: 1}}>
                    <div style={{fontSize: 13, fontWeight: 600}}>Seguimiento programado</div>
                    <div style={{fontSize: 11, color: "var(--fg-3)", marginTop: 2}}>
                      {new Date(sb.proximo_seguimiento).toLocaleDateString("es-ES", { weekday: "long", day: "2-digit", month: "long" })}
                    </div>
                  </div>
                </div>
              ) : (
                <div style={{padding: 8, fontSize: 12, color: "var(--fg-3)"}}>Sin acciones programadas.</div>
              )}
              <button className="btn secondary" style={{marginTop: 12, width: "100%", justifyContent: "center"}}>
                <Icons.Plus/> Crear tarea o evento
              </button>
            </Card>

            {/* Asignación */}
            <Card title="Asignación">
              <div style={{display: "flex", flexDirection: "column", gap: 10}}>
                <div>
                  <div className="kv-lbl">Responsable principal</div>
                  <div style={{display: "flex", alignItems: "center", gap: 8, marginTop: 6}}>
                    <div className="sb-avatar" style={{width: 24, height: 24, fontSize: 9}}>
                      {(sb.responsable_raw || "??").split(" ").map(p => p[0]).slice(0,2).join("").toUpperCase()}
                    </div>
                    <span style={{fontSize: 13}}>{sb.responsable_raw || "Sin asignar"}</span>
                  </div>
                </div>
              </div>
              <button className="btn ghost xs" style={{marginTop: 12}}>Reasignar →</button>
            </Card>

            {/* Plantillas WhatsApp */}
            <Card title="Plantillas WhatsApp">
              <div style={{display: "flex", flexDirection: "column", gap: 6}}>
                {["Primer contacto", "Recordatorio visita", "Compartir nueva ficha", "Pedir feedback"].map((t, i) => (
                  <div key={i} style={{padding: "8px 10px", border: "1px solid var(--border-1)", borderRadius: 2, fontSize: 12, cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
                    {t}
                    <Icons.Whatsapp size={14}/>
                  </div>
                ))}
              </div>
            </Card>
          </div>
        </div>
      )}

      {tab === "datos" && (
        <Card title="Todos los datos del contacto">
          <div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, padding: 4}}>
            <KV lbl="Nombre completo" value={c.displayName || c.name}/>
            <KV lbl="Tipo" value={ui.clienteType ? ui.clienteType(c.typeKey) : c.type}/>
            <KV lbl="Estado comercial" value={sb.estado ? (ui.estado ? ui.estado(sb.estado) : sb.estado) : null}/>
            <KV lbl="Teléfono" value={c.phone}/>
            <KV lbl="Email" value={c.email} mono/>
            <KV lbl="DNI / CIF" value={sb.dni_cif} mono/>
            <KV lbl="Dirección" value={sb.direccion}/>
            <KV lbl="CP" value={sb.cp}/>
            <KV lbl="Figura legal" value={sb.figura_legal ? (ui.figura ? ui.figura(sb.figura_legal) : sb.figura_legal) : null}/>
            <KV lbl="Origen del contacto" value={ui.origin ? ui.origin(c.originKey) : c.origin}/>
            <KV lbl="Motivación" value={sb.motivacion ? (ui.motivacion ? ui.motivacion(sb.motivacion) : sb.motivacion) : null}/>
            <KV lbl="Tipo de inmueble" value={sb.tipo_inmueble_interes ? sb.tipo_inmueble_interes.toUpperCase() : null}/>
            <KV lbl="Tipo de proveedor" value={sb.tipo_proveedor ? (ui.provType ? ui.provType(sb.tipo_proveedor) : sb.tipo_proveedor) : null}/>
            <KV lbl="Presupuesto mínimo" value={c.budget > 0 ? window.fmtEUR(c.budget) : null}/>
            <KV lbl="Presupuesto máximo" value={c.budgetMax > 0 ? window.fmtEUR(c.budgetMax) : null}/>
            <KV lbl="Zona de interés" value={c.zone}/>
            <KV lbl="Financiación" value={c.financing && c.financing !== "—" ? c.financing : null}/>
            <KV lbl="RRSS" value={sb.rrss}/>
            <KV lbl="Entrada al pipeline" value={sb.entrada_al_pipeline ? new Date(sb.entrada_al_pipeline).toLocaleDateString("es-ES") : null}/>
            <KV lbl="Días en pipeline" value={sb.dias_en_pipeline != null ? sb.dias_en_pipeline + " días" : null}/>
            <KV lbl="Próximo seguimiento" value={sb.proximo_seguimiento ? new Date(sb.proximo_seguimiento).toLocaleDateString("es-ES") : null}/>
            <KV lbl="Responsable" value={sb.responsable_raw}/>
            <KV lbl="Último contacto" value={c.lastContact !== "—" ? c.lastContact : null}/>
            <KV lbl="Notion ID" value={sb.notion_id} mono/>
          </div>
        </Card>
      )}

      {tab === "proyectos" && (
        <Card title="Proyectos asociados">
          <div className="empty">
            <div className="icon-wrap"><Icons.Folder/></div>
            <div style={{fontSize: 13, color: "var(--fg-2)", marginBottom: 6}}>
              Aún no hay proyectos asociados a este cliente.
            </div>
            <div style={{fontSize: 11, color: "var(--fg-3)", marginBottom: 16}}>
              Cuando importemos los Proyectos de Notion (próxima ola), aparecerán aquí automáticamente las operaciones donde este cliente participa como comprador, vendedor, propietario o proveedor.
            </div>
            <button className="btn primary"><Icons.Plus/> Asociar manualmente</button>
          </div>
        </Card>
      )}

      {tab === "documentos" && (
        <Card title={`Documentos del cliente · ${docsCliente.length}`} right={<button className="btn xs primary" onClick={() => setSubiendoDoc(true)}><Icons.Upload/> Subir</button>}>
          {errDoc && (
            <div className="sb-login-err" style={{ margin: "10px 16px" }}><span>{errDoc}</span></div>
          )}
          {docsCliente.map((d, i) => (
            <div className="doc" key={i}>
              <div className={"ico-doc " + (d.kind || "").toLowerCase()}>{d.kind || "DOC"}</div>
              <div className="doc-meta">
                <div className="doc-name">{d.name}</div>
                <div className="doc-sub"><span>{d.kind} · {d.size}</span><span>·</span><span>{d.date}</span></div>
              </div>
              <div className="doc-actions">
                <button className="btn xs ghost" title="Descargar"
                        onClick={() => descargar(d)}><Icons.Download/></button>
              </div>
            </div>
          ))}
          {docsCliente.length === 0 && (
          <div className="empty">
            <div className="icon-wrap"><Icons.Doc/></div>
            Sin documentos vinculados a este cliente todavía.
            <div style={{marginTop: 12, fontSize: 11, color: "var(--fg-3)"}}>
              Aquí guardaremos: DNI, contrato de búsqueda, hoja de encargo, pre-aprobación bancaria, etc.
            </div>
          </div>
          )}
        </Card>
      )}

      {tab === "historial" && (
        <Card title="Historial de interacciones" b={false}>
          <div className="empty">
            <div className="icon-wrap"><Icons.Clock/></div>
            Sin interacciones registradas.
            <div style={{marginTop: 12, fontSize: 11, color: "var(--fg-3)"}}>
              Llamadas, WhatsApp, emails y visitas aparecerán aquí cuando importemos las Interacciones de Notion o cuando se generen desde el CRM.
            </div>
          </div>
        </Card>
      )}

      {subiendoDoc && window.SubirDocumentoModal && (
        <window.SubirDocumentoModal
          clienteId={cUid}
          onClose={() => setSubiendoDoc(false)}
          onSubido={trasSubirDoc}
        />
      )}
    </>
  );
};

window.ClientDetail = ClientDetail;
