/* Contacts — searchable list + detail panel over e31_contacts (read-only).
   Detail stitches the contact's jobs, calls and appointments. */

const { Card: ContactCard, Eyebrow: ContactEyebrow } = window.Ds1Threshold_e046d3;

function Avatar({ first, last, size = 38 }) {
  const initials = ((first || "")[0] || "") + ((last || "")[0] || "");
  return (
    <span style={{ width: size, height: size, flexShrink: 0, borderRadius: "var(--radius-md)", background: "var(--color-primary-soft)", border: "1px solid var(--color-primary-ring)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)", fontWeight: 700, fontSize: size * 0.34 }}>{initials.toUpperCase()}</span>
  );
}

function Contacts() {
  const CRM = window.CRM;
  const sorted = [...CRM.contacts].sort((a, b) => (a.last_name + a.first_name).localeCompare(b.last_name + b.first_name));
  const [q, setQ] = React.useState("");
  const [selId, setSelId] = React.useState(sorted[0] && sorted[0].id);

  const t = q.trim().toLowerCase();
  const list = sorted.filter((c) => !t || [`${c.first_name} ${c.last_name}`, c.phone, c.email].some((v) => (v || "").toLowerCase().includes(t)));
  const sel = CRM.contacts.find((c) => c.id === selId) || list[0];

  const jobs = sel ? CRM.jobs.filter((j) => j.contact_id === sel.id) : [];
  const calls = sel ? CRM.calls.filter((c) => c.contact_id === sel.id).sort((a, b) => (a.date < b.date ? 1 : -1)) : [];
  const appts = sel ? CRM.appointments.filter((a) => a.contact_id === sel.id) : [];

  return (
    <div style={{ maxWidth: "var(--content-max)", margin: "0 auto" }}>
      <div style={{ marginBottom: 22, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>Contacts</h1>
          <p style={{ margin: "4px 0 0", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Read-only mirror of Engine 31 contacts · jobs, calls &amp; appointments</p>
        </div>
        <window.CRMSyncIndicator />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "360px 1fr", gap: 24, alignItems: "start" }}>
        {/* Master list */}
        <ContactCard padding="none" style={{ overflow: "hidden" }}>
          <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border-subtle)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--input-bg)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", padding: "8px 11px" }}>
              <Icon name="Search" size={15} color="var(--text-muted)" />
              <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search contacts…" style={{ border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", width: "100%" }} />
            </div>
          </div>
          <div style={{ maxHeight: 620, overflowY: "auto" }}>
            {list.map((c) => {
              const on = sel && c.id === sel.id;
              return (
                <button key={c.id} onClick={() => setSelId(c.id)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", border: "none", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer", textAlign: "left", background: on ? "var(--color-primary-soft)" : "transparent", borderLeft: `3px solid ${on ? "var(--color-primary-deep)" : "transparent"}` }}>
                  <Avatar first={c.first_name} last={c.last_name} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{c.first_name} {c.last_name}</div>
                    <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.phone}</div>
                  </div>
                </button>
              );
            })}
            {list.length === 0 && <div style={{ padding: 28, textAlign: "center", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>No contacts found.</div>}
          </div>
        </ContactCard>

        {/* Detail */}
        {sel && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <ContactCard padding="md">
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar first={sel.first_name} last={sel.last_name} size={52} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <h2 style={{ margin: 0, fontSize: "var(--text-xl)", fontWeight: 700, color: "var(--text-primary)" }}>{sel.first_name} {sel.last_name}</h2>
                  <div style={{ display: "flex", gap: 16, marginTop: 4, flexWrap: "wrap" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--text-sm)", color: "var(--text-muted)" }}><Icon name="Phone" size={13} />{sel.phone}</span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--text-sm)", color: "var(--text-muted)" }}><Icon name="Mail" size={13} />{sel.email}</span>
                  </div>
                </div>
                <span style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", fontVariantNumeric: "tabular-nums" }}>{sel.id}</span>
              </div>
            </ContactCard>

            {/* Jobs */}
            <ContactCard padding="md">
              <ContactEyebrow size="2xs" style={{ marginBottom: 12 }}>Jobs · {jobs.length}</ContactEyebrow>
              {jobs.length === 0 && <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>No jobs linked to this contact.</div>}
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {jobs.map((j) => (
                  <div key={j.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: "var(--radius-md)", background: "var(--surface-sunken)" }}>
                    <window.CRMSiloChip silo={j.silo} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{j.full_address}</div>
                    </div>
                    <window.CRMStatusPill silo={j.silo} status={j.status} />
                    <span style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>{j.id}</span>
                  </div>
                ))}
              </div>
            </ContactCard>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              {/* Calls */}
              <ContactCard padding="md">
                <ContactEyebrow size="2xs" style={{ marginBottom: 12 }}>Call Log · {calls.length}</ContactEyebrow>
                {calls.length === 0 && <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>No calls logged.</div>}
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {calls.map((c) => (
                    <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 28, height: 28, flexShrink: 0, borderRadius: "var(--radius-md)", background: "var(--surface-sunken)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)" }}><Icon name={c.direction === "inbound" ? "PhoneIncoming" : "PhoneOutgoing"} size={14} /></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--text-primary)" }}>{c.outcome}</div>
                        <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-muted)" }}>{CRM.fmtDay(c.date)} · {c.duration_sec ? Math.round(c.duration_sec/60) + "m " + (c.duration_sec%60) + "s" : "no answer"}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </ContactCard>

              {/* Appointments */}
              <ContactCard padding="md">
                <ContactEyebrow size="2xs" style={{ marginBottom: 12 }}>Appointments · {appts.length}</ContactEyebrow>
                {appts.length === 0 && <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>No appointments.</div>}
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {appts.map((a) => (
                    <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 28, height: 28, flexShrink: 0, borderRadius: "var(--radius-md)", background: "var(--surface-sunken)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)" }}><Icon name="CalendarClock" size={14} /></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--text-primary)" }}>{a.type}</div>
                        <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-muted)" }}>{CRM.fmtDay(a.date)} · {a.time}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </ContactCard>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Contacts = Contacts;
