// Woodbury Operator — Tenant Profile (view + edit + unit assignment).
// Registers window.TenantProfileScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, Avatar, ProgressBar, IconTile, Eyebrow, Input, Select, Modal, Textarea } = NS;

  const HISTORY = [
    { unit: "AC Leak", meta: "Reported 2 hours ago · HVAC notified", icon: "wind", tone: "danger", badge: "Urgent", badgeTone: "danger" },
    { unit: "Repaint request", meta: "Completed 12 Mar", icon: "paintbrush", tone: "sunken", badge: "Resolved", badgeTone: "success" },
    { unit: "Wi-Fi router swap", meta: "Completed 02 Feb", icon: "wifi", tone: "sunken", badge: "Resolved", badgeTone: "success" },
  ];
  const DOCS = [
    { name: "Signed Tenancy Agreement.pdf", meta: "248 KB · Signed 12 Apr" },
    { name: "ID Verification.pdf", meta: "512 KB · Verified 10 Apr" },
  ];
  const TIMELINE = [
    { icon: "wrench", tone: "danger", title: "Maintenance reported", body: "AC Leak in House 1 — marked urgent, HVAC notified.", time: "Today · 09:12" },
    { icon: "message-square", tone: "brand", title: "Message received", body: "“The unit is making a loud grinding noise.”", time: "Today · 09:10" },
    { icon: "clipboard-check", tone: "accent", title: "Routine inspection passed", body: "Quarterly inspection completed — no issues found.", time: "14 Mar · 11:30" },
    { icon: "paintbrush", tone: "success", title: "Maintenance resolved", body: "Repaint request completed and signed off.", time: "12 Mar · 16:40" },
    { icon: "file-signature", tone: "success", title: "Lease signed", body: "12-month tenancy agreement executed for House 1.", time: "01 Jun 2024 · 10:00" },
    { icon: "shield-check", tone: "success", title: "Identity verified", body: "National ID verification cleared during screening.", time: "28 May 2024 · 14:05" },
    { icon: "user-plus", tone: "sunken", title: "Applicant onboarded", body: "Profile created and invited to the resident portal.", time: "20 May 2024 · 09:00" },
  ];

  function Field({ label, value, editing, onChange, type }) {
    if (editing) return <Input label={label} defaultValue={value} type={type} onChange={(e) => onChange && onChange(e.target.value)} />;
    return (
      <div style={{ background: "var(--cream-50)", borderRadius: "var(--radius-md)", padding: "14px 16px" }}>
        <div style={{ fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{label}</div>
        <div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)", marginTop: 4, wordBreak: "break-word" }}>{value}</div>
      </div>
    );
  }

  function TenantProfileScreen({ onBack }) {
    const [tenant, setTenant] = React.useState({
      name: "Kofi Mensah", email: "kofi.mensah@yahoo.com", phone: "+233 20 887 3341", avatar: "../../assets/images/av-kofi.jpg",
      emergency: "Akosua Mensah · +233 24 118 0092", nationalId: "GHA-724901183-6",
      property: "Lashibi Townhouses", unit: "House 1", moveIn: "01 Jun 2024", ends: "28 May 2026", left: 28, term: "12 months", status: "Active",
    });
    const [editing, setEditing] = React.useState(false);
    const [draft, setDraft] = React.useState(tenant);
    const [assign, setAssign] = React.useState(false);
    const [note, setNote] = React.useState(false);
    const [noteText, setNoteText] = React.useState("");
    const [notes, setNotes] = React.useState([]);
    const [docModal, setDocModal] = React.useState(false);
    const [docName, setDocName] = React.useState("");
    const [docFolder, setDocFolder] = React.useState("Tenancy Agreements");
    const [, forceDocs] = React.useReducer((x) => x + 1, 0);

    React.useEffect(() => { if (window.WBFocus && window.WBFocus.kind === "edit-tenant") { setDraft(tenant); setEditing(true); window.WBFocus = null; } }, []);
    const [aProp, setAProp] = React.useState(tenant.property);
    const [aUnit, setAUnit] = React.useState(tenant.unit);

    const startEdit = () => { setDraft(tenant); setEditing(true); };
    const save = () => { setTenant(draft); setEditing(false); window.WBToast("Tenant profile updated"); };
    const set = (k, v) => setDraft((d) => ({ ...d, [k]: v }));

    const confirmAssign = () => {
      setTenant((t) => ({ ...t, property: aProp, unit: aUnit }));
      setAssign(false);
      window.WBToast("Unit reassigned to " + aProp + " · " + aUnit);
    };
    const unlink = async () => {
      const yes = await window.WBConfirm({ title: "Unlink unit?", message: "This removes " + tenant.name + " from " + tenant.unit + ". Their lease will need reassignment.", confirmLabel: "Unlink", danger: true });
      if (!yes) return;
      setTenant((t) => ({ ...t, property: "—", unit: "Unassigned", status: "Unassigned" }));
      window.WBToast("Unit unlinked", "danger");
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1200 }}>
        <window.WBPageHeader eyebrow="Resident" title="Tenant Profile"
          sub="Full resident record, unit assignment, and history."
          actions={<React.Fragment>
            <Button variant="secondary" icon="arrow-left" onClick={onBack}>Back</Button>
            {editing
              ? <React.Fragment><Button variant="ghost" onClick={() => setEditing(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={save}>Save</Button></React.Fragment>
              : <Button variant="primary" icon="pencil" onClick={startEdit}>Edit Profile</Button>}
          </React.Fragment>} />

        {/* Identity */}
        <Card style={{ padding: 28 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
            <Avatar src={tenant.avatar} name={tenant.name} size={84} />
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <h2 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 26, color: "var(--text-heading)" }}>{tenant.name}</h2>
                {tenant.status === "Active" ? <Badge tone="success" dot>Active Tenant</Badge> : <Badge tone="neutral">{tenant.status}</Badge>}
              </div>
              <p style={{ margin: "6px 0 0", fontSize: 14, color: "var(--text-muted)" }}>{tenant.property} · {tenant.unit}</p>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <Button variant="secondary" icon="message-square" onClick={() => window.WBToast("Messaging " + tenant.name)}>Message</Button>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginTop: 24 }}>
            <Field label="Full name" value={editing ? draft.name : tenant.name} editing={editing} onChange={(v) => set("name", v)} />
            <Field label="Email" value={editing ? draft.email : tenant.email} editing={editing} onChange={(v) => set("email", v)} />
            <Field label="Phone" value={editing ? draft.phone : tenant.phone} editing={editing} onChange={(v) => set("phone", v)} />
            <Field label="National ID" value={editing ? draft.nationalId : tenant.nationalId} editing={editing} onChange={(v) => set("nationalId", v)} />
            <Field label="Emergency contact" value={editing ? draft.emergency : tenant.emergency} editing={editing} onChange={(v) => set("emergency", v)} />
            <Field label="Move-in date" value={editing ? draft.moveIn : tenant.moveIn} editing={editing} onChange={(v) => set("moveIn", v)} />
          </div>
        </Card>

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 24, alignItems: "start" }}>
          {/* Unit assignment */}
          <Card>
            <CardHeader title="Unit Assignment" action={tenant.unit === "Unassigned"
              ? <Button variant="primary" size="sm" icon="link" onClick={() => setAssign(true)}>Assign Unit</Button>
              : <Button variant="secondary" size="sm" icon="repeat" onClick={() => { setAProp(tenant.property); setAUnit(tenant.unit); setAssign(true); }}>Change Unit</Button>} />
            <div style={{ padding: 24 }}>
              {tenant.unit === "Unassigned" ? (
                <div style={{ textAlign: "center", padding: "24px 0", color: "var(--text-muted)" }}>
                  <span className="wb-ico" style={{ width: 32, height: 32, display: "inline-flex" }}><i data-lucide="unlink"></i></span>
                  <div style={{ fontSize: 14, marginTop: 10 }}>No unit linked. Assign one to activate the tenancy.</div>
                </div>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                  <IconTile icon="home" tone="brand" size={52} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 18, color: "var(--text-heading)" }}>{tenant.unit}</div>
                    <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{tenant.property} · linked since {tenant.moveIn}</div>
                  </div>
                  <Button variant="ghost" size="sm" icon="unlink" onClick={unlink}>Unlink</Button>
                </div>
              )}
            </div>
            <div style={{ borderTop: "1px solid var(--border)", padding: 24 }}>
              <Eyebrow>Maintenance history · {tenant.unit}</Eyebrow>
              <div style={{ display: "flex", flexDirection: "column", marginTop: 12 }}>
                {HISTORY.map((h, i) => (
                  <div key={h.unit} style={{ display: "flex", gap: 14, alignItems: "center", padding: "12px 0", borderTop: i ? "1px solid var(--border)" : "none" }}>
                    <IconTile icon={h.icon} tone={h.tone} size={38} />
                    <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{h.unit}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{h.meta}</div></div>
                    <Badge tone={h.badgeTone} dot={h.badgeTone === "success"}>{h.badge}</Badge>
                  </div>
                ))}
              </div>
            </div>
          </Card>

          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <Card style={{ padding: 24 }}>
              <h3 style={{ margin: "0 0 14px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 18, color: "var(--text-heading)" }}>Lease</h3>
              {tenant.unit === "Unassigned" ? (
                <p style={{ margin: 0, fontSize: 13, color: "var(--text-muted)" }}>No active lease — link a unit first.</p>
              ) : (
                <React.Fragment>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}><span style={{ color: "var(--danger)", fontWeight: 600 }}>{tenant.left} days left</span><span>Ends {tenant.ends}</span></div>
                  <ProgressBar value={8} tone="danger" style={{ marginBottom: 16 }} />
                  <Button variant="primary" size="sm" full onClick={() => window.WBToast("Renewal initiated for " + tenant.name)}>Initiate Renewal</Button>
                </React.Fragment>
              )}
            </Card>
            <Card style={{ padding: 24 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <Eyebrow>Documents</Eyebrow>
                <Button variant="ghost" size="sm" icon="upload" onClick={() => { setDocName(""); setDocFolder("Tenancy Agreements"); setDocModal(true); }}>Upload</Button>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 14 }}>
                {(window.WB_TENANT_DOCS[tenant.name] || []).map((d) => (
                  <div key={d.name} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <IconTile icon="file-text" tone="sunken" size={36} />
                    <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 13, color: "var(--text-heading)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</div><div style={{ fontSize: 11, color: "var(--text-muted)" }}>{d.meta} · {d.folder}</div></div>
                    <Button variant="ghost" size="sm" icon="download" onClick={() => window.WBToast("Downloading " + d.name)} />
                  </div>
                ))}
                {(window.WB_TENANT_DOCS[tenant.name] || []).length === 0 && <div style={{ fontSize: 13, color: "var(--text-muted)", padding: "8px 0" }}>No documents yet.</div>}
              </div>
            </Card>
          </div>
        </div>

        {/* Activity timeline */}
        <Card>
          <CardHeader title="Activity Timeline" action={<Button variant="secondary" size="sm" icon="plus" onClick={() => setNote(true)}>Log Note</Button>} />
          <div style={{ padding: "24px 28px" }}>
            {notes.concat(TIMELINE).map((e, i, arr) => {
              const tones = { danger: ["var(--danger-bg)", "var(--danger)"], brand: ["var(--walnut-100)", "var(--walnut-700)"], accent: ["rgba(194,125,72,0.14)", "var(--terracotta-600)"], success: ["var(--success-bg)", "var(--success)"], sunken: ["var(--cream-100)", "var(--gray-500)"] }[e.tone] || ["var(--cream-100)", "var(--gray-500)"];
              return (
                <div key={i} style={{ display: "flex", gap: 16 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                    <div style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: tones[0], display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><span className="wb-ico" style={{ width: 17, height: 17, color: tones[1] }}><i data-lucide={e.icon}></i></span></div>
                    {i < arr.length - 1 && <div style={{ flex: 1, width: 2, background: "var(--border)", margin: "4px 0" }} />}
                  </div>
                  <div style={{ flex: 1, paddingBottom: i < arr.length - 1 ? 22 : 0 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                      <span style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{e.title}</span>
                      <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{e.time}</span>
                    </div>
                    <p style={{ margin: "3px 0 0", fontSize: 13, lineHeight: 1.5, color: "var(--text-body)" }}>{e.body}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* Log note modal */}
        <Modal open={note} onClose={() => setNote(false)} icon="pencil" title="Log Note" subtitle={"Add an activity note for " + tenant.name} width={460}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setNote(false)}>Cancel</Button><Button variant="primary" icon="check" disabled={!noteText.trim()} onClick={() => { setNotes((n) => [{ icon: "sticky-note", tone: "accent", title: "Note added", body: noteText.trim(), time: "Just now" }, ...n]); setNoteText(""); setNote(false); window.WBToast("Note logged"); }}>Save Note</Button></React.Fragment>}>
          <Textarea label="Note" placeholder="e.g. Called tenant about renewal; will confirm next week." value={noteText} onChange={(e) => setNoteText(e.target.value)} />
        </Modal>

        {/* Upload document modal */}
        <Modal open={docModal} onClose={() => setDocModal(false)} icon="upload" title="Upload Document" subtitle={"Link a file to " + tenant.name}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setDocModal(false)}>Cancel</Button><Button variant="primary" icon="check" disabled={!docName.trim()} onClick={() => {
            const nm = docName.trim().endsWith(".pdf") ? docName.trim() : docName.trim() + ".pdf";
            window.WBAddTenantDoc(tenant.name, { name: nm, meta: "Uploaded just now", folder: docFolder });
            setNotes((n) => [{ icon: "file-text", tone: "brand", title: "Document uploaded", body: nm + " filed under " + docFolder + ".", time: "Just now" }, ...n]);
            setDocModal(false); forceDocs(); window.WBToast(nm + " saved to " + docFolder);
          }}>Upload</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ background: "var(--cream-50)", borderRadius: "var(--radius-md)", padding: 14, fontSize: 13, color: "var(--text-body)" }}>The document is saved to the Documents repository under the chosen folder and linked to this tenant's profile.</div>
            <Input label="Document name" placeholder="e.g. Signed Tenancy Agreement" value={docName} onChange={(e) => setDocName(e.target.value)} />
            <Select label="Folder" value={docFolder} onChange={(e) => setDocFolder(e.target.value)} options={["Tenancy Agreements", "Screening", "Insurance", "Inspection Reports"]} />
            <window.WBImageUpload label="Attach file" />
          </div>
        </Modal>

        {/* Assign / change unit modal */}
        <Modal open={assign} onClose={() => setAssign(false)} icon="link" title={tenant.unit === "Unassigned" ? "Assign Unit" : "Change Unit"} subtitle={"Link " + tenant.name + " to an apartment."}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setAssign(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={confirmAssign}>Confirm Assignment</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ background: "var(--cream-50)", borderRadius: "var(--radius-md)", padding: 14, fontSize: 13, color: "var(--text-body)" }}>
              How it works: a tenant is linked to one unit at a time. Reassigning moves their lease and maintenance history to the new unit and frees the old one for a new applicant.
            </div>
            <Select label="Property" value={aProp} onChange={(e) => { setAProp(e.target.value); const u = window.WBunitsFor(e.target.value, true); setAUnit(u[0] || "No vacant units"); }} options={window.WB_SITES} />
            <Select label="Unit (vacant)" value={aUnit} onChange={(e) => setAUnit(e.target.value)} options={window.WBunitsFor(aProp, true).length ? window.WBunitsFor(aProp, true) : ["No vacant units"]} />
            <Input label="Effective date" type="date" />
          </div>
        </Modal>
      </div>
    );
  }
  window.TenantProfileScreen = TenantProfileScreen;
})();
