/* Properties list — the signature data grid. window.PropertiesScreen */
const { useState } = React;
function StatusCell({ status }) {
  return <StatusBadge status={status} />;
}

function TaskCell({ assignee }) {
  if (!assignee) return <Badge tone="neutral">+ Add task</Badge>;
  const isLabel = !window.PT_DATA.team.includes(assignee);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      {isLabel
        ? <Icon name="tag" size={13} color="var(--text-muted)" />
        : <Avatar name={assignee} size="xs" />}
      <span style={{ fontSize: "var(--text-sm)", color: "var(--text-body)", fontWeight: 500 }}>{assignee}</span>
    </span>
  );
}

function Th({ children, sortable, active, w }) {
  return (
    <th style={{ textAlign: "left", padding: "9px 14px", width: w, position: "sticky", top: 0, background: "var(--surface-sunken)", borderBottom: "1px solid var(--border-default)", zIndex: 1 }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", fontWeight: 700, color: active ? "var(--text-brand)" : "var(--text-muted)", cursor: sortable ? "pointer" : "default" }}>
        {children}{sortable && <Icon name={active ? "arrow-down" : "chevrons-up-down"} size={12} />}
      </span>
    </th>
  );
}

function PropertyRow({ p, onOpen }) {
  const [hover, setHover] = useState(false);
  const followNotes = p.notes.filter((n) => n.follow === p.followDate).map((n) => ({ author: n.author, subject: n.subject, body: n.body, assignee: n.assignee }));
  return (
    <tr onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={() => onOpen(p)}
      style={{ cursor: "pointer", background: hover ? "var(--surface-hover)" : "var(--surface-card)", borderBottom: "1px solid var(--border-subtle)" }}>
      <td style={{ padding: "10px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <img src={p.thumb} alt="" style={{ width: 52, height: 40, borderRadius: "var(--radius-sm)", objectFit: "cover", flex: "none", background: "var(--slate-100)" }} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: "var(--text-base)", whiteSpace: "nowrap" }}>{p.address}</div>
            <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", whiteSpace: "nowrap" }} className="tnum">{p.city}, {p.state} · {p.county} County · {p.id}</div>
          </div>
        </div>
      </td>
      <td style={{ padding: "10px 14px" }}><StatusCell status={p.status} /></td>
      <td style={{ padding: "10px 14px" }}><span className="tnum" style={{ fontFamily: "var(--font-mono)", fontSize: "var(--text-sm)", color: "var(--text-strong)", fontWeight: 500 }}>{p.ask ? "$" + p.ask.toLocaleString() : "—"}</span></td>
      <td style={{ padding: "10px 14px" }}><Badge tone={p.motivation === "High" ? "action" : p.motivation === "Medium" ? "warning" : "neutral"}>{p.motivation}</Badge></td>
      <td style={{ padding: "10px 14px" }}><TaskCell assignee={p.notes.find(n => n.assignee && n.assignee !== "Unassigned")?.assignee} /></td>
      <td style={{ padding: "10px 14px" }}>
        {p.followDate === "—" ? <span style={{ color: "var(--text-subtle)" }}>—</span>
          : <FollowUpCell date={p.followDate} overdue={p.overdue} notes={followNotes.length ? followNotes : [{ author: p.notes[0]?.author || "—", subject: p.notes[0]?.subject || "", body: p.notes[0]?.body || "", assignee: p.notes[0]?.assignee }]} />}
      </td>
      <td style={{ padding: "10px 8px", textAlign: "right" }}>
        <span style={{ opacity: hover ? 1 : 0.35 }}><Icon name="chevron-right" size={18} color="var(--text-muted)" /></span>
      </td>
    </tr>
  );
}

function PropertiesScreen({ onOpen, onAddColumn }) {
  const d = window.PT_DATA;
  const [filter, setFilter] = useState("all");
  const counts = { all: d.properties.length, active: d.properties.filter(p => p.status === "active").length, due: d.properties.filter(p => p.overdue).length };
  const rows = filter === "due" ? d.properties.filter(p => p.overdue) : filter === "active" ? d.properties.filter(p => p.status === "active") : d.properties;
  return (
    <div style={{ padding: 22 }}>
      {/* Filter / toolbar */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ display: "inline-flex", background: "var(--surface-sunken)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", padding: 3, gap: 2 }}>
          {[["all", "All deals"], ["active", "Active"], ["due", "Follow-ups due"]].map(([k, label]) => (
            <button key={k} onClick={() => setFilter(k)} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: "var(--radius-sm)", border: "none", cursor: "pointer", fontSize: "var(--text-sm)", fontWeight: 600, fontFamily: "var(--font-sans)", background: filter === k ? "var(--surface-card)" : "transparent", color: filter === k ? "var(--text-strong)" : "var(--text-muted)", boxShadow: filter === k ? "var(--shadow-xs)" : "none" }}>
              {label}<span style={{ fontSize: "var(--text-2xs)", color: k === "due" ? "var(--ember-600)" : "var(--text-subtle)", fontWeight: 700 }}>{counts[k]}</span>
            </button>
          ))}
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <Button variant="secondary" size="sm" icon="sliders-horizontal" onClick={onAddColumn}>Columns</Button>
          <Button variant="secondary" size="sm" icon="filter">Filter</Button>
          <Button variant="brand" size="sm" icon="plus" onClick={() => navigate("/properties/new")}>Add property</Button>
        </div>
      </div>

      {/* Grid */}
      <div style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", overflow: "hidden", boxShadow: "var(--shadow-xs)" }}>
        <div className="pt-scroll-x">
        <table style={{ width: "100%", minWidth: 940, borderCollapse: "collapse" }}>
          <thead>
            <tr>
              <Th sortable w={320}>Property</Th>
              <Th sortable>Status</Th>
              <Th sortable>Asking</Th>
              <Th>Motivation <span title="Custom column" style={{textTransform:"none",letterSpacing:0}}></span></Th>
              <Th>Task</Th>
              <Th sortable active>Follow-up</Th>
              <th style={{ background: "var(--surface-sunken)", borderBottom: "1px solid var(--border-default)" }}></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((p) => <PropertyRow key={p.id} p={p} onOpen={onOpen} />)}
          </tbody>
        </table>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12, fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>
        <span>Showing {rows.length} of {d.properties.length} deals</span>
        <div style={{ display: "flex", gap: 4 }}>
          <IconButton icon="chevron-left" label="Previous" variant="solid" size="sm" />
          <IconButton icon="chevron-right" label="Next" variant="solid" size="sm" />
        </div>
      </div>
    </div>
  );
}
window.PropertiesScreen = PropertiesScreen;
