// Woodbury Operator — Documents. Registers window.DocumentsScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, Button, Badge, IconTile, Input, Modal, Select } = NS;

  const FOLDERS = [
    { name: "Tenancy Agreements", count: 42, icon: "file-signature", tone: "brand" },
    { name: "Land Registration", count: 6, icon: "landmark", tone: "accent" },
    { name: "Insurance", count: 18, icon: "shield", tone: "success" },
    { name: "Inspection Reports", count: 27, icon: "clipboard-check", tone: "sunken" },
  ];
  const FILES = [
    { name: "Signed Tenancy Agreement.pdf", meta: "Lashibi Townhouses · 248 KB", date: "Signed 12 Apr", tag: "Signed", tagTone: "success" },
    { name: "Land Registration Papers.pdf", meta: "Cantonments City · 1.1 MB", date: "Uploaded 30 Mar", tag: "Verified", tagTone: "brand" },
    { name: "Insurance Certificate 2026.pdf", meta: "Portfolio-wide · 512 KB", date: "Uploaded 04 Feb", tag: "Active", tagTone: "success" },
    { name: "Lashibi Townhouses Floor Plan.pdf", meta: "Lashibi Townhouses · 3.4 MB", date: "Uploaded 21 Jan", tag: "Reference", tagTone: "neutral" },
    { name: "Mirage Inspection.pdf", meta: "Mirage · 890 KB", date: "Uploaded 09 Jan", tag: "Review", tagTone: "warning" },
  ];

  function RowMenu({ file, onClose }) {
    const act = async (label) => {
      onClose();
      if (label === "Delete") {
        const yes = await window.WBConfirm({ title: "Delete document?", message: '"' + file.name + '" will be permanently removed.', confirmLabel: "Delete", danger: true });
        if (!yes) return;
        window.WBToast("Deleted " + file.name, "danger");
        return;
      }
      window.WBToast(label + " · " + file.name);
    };
    return (
      <div style={{ position: "absolute", right: 0, top: "100%", marginTop: 4, zIndex: 20, minWidth: 168, background: "var(--surface)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", border: "1px solid var(--border)", overflow: "hidden", padding: 6 }}>
        {[["Rename", "pencil"], ["Share link", "link"], ["Move to folder", "folder-input"], ["Delete", "trash-2"]].filter(([label]) => label !== "Delete" || window.WBRoleKey === "super").map(([label, icon]) => (
          <button key={label} onClick={() => act(label)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", border: "none", background: "transparent", cursor: "pointer", padding: "9px 10px", borderRadius: 8, fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: label === "Delete" ? "var(--danger)" : "var(--text-heading)", textAlign: "left" }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--cream-50)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
            <span className="wb-ico" style={{ width: 15, height: 15 }}><i data-lucide={icon}></i></span>{label}
          </button>
        ))}
      </div>
    );
  }

  function DocumentsScreen() {
    const [upload, setUpload] = React.useState(false);
    const [menu, setMenu] = React.useState(null); // file name with open menu
    React.useEffect(() => {
      const onClick = () => setMenu(null);
      document.addEventListener("click", onClick);
      return () => document.removeEventListener("click", onClick);
    }, []);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Records" title="Documents"
          sub="Central repository for contracts, titles, and compliance records."
          actions={<Button variant="primary" icon="upload" onClick={() => setUpload(true)}>Upload</Button>} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20 }}>
          {FOLDERS.map((f) => (
            <Card key={f.name} style={{ padding: 20, display: "flex", alignItems: "center", gap: 14, cursor: "pointer" }} onClick={() => window.WBToast("Opening " + f.name)}>
              <IconTile icon={f.icon} tone={f.tone} size={44} />
              <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{f.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{f.count} files</div></div>
            </Card>
          ))}
        </div>
        <Card>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 24px", borderBottom: "1px solid var(--border)" }}>
            <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>Recent Documents</h3>
            <Input icon="search" placeholder="Search files..." size="sm" containerStyle={{ width: 280 }} />
          </div>
          {FILES.map((f, i) => (
            <div key={f.name} style={{ display: "grid", gridTemplateColumns: "2fr 1fr 0.8fr 0.5fr", gap: 16, alignItems: "center", padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <IconTile icon="file-text" tone="sunken" size={40} />
                <div><div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{f.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{f.meta}</div></div>
              </div>
              <span style={{ fontSize: 13, color: "var(--text-body)" }}>{f.date}</span>
              <div><Badge tone={f.tagTone}>{f.tag}</Badge></div>
              <div style={{ textAlign: "right", display: "flex", gap: 4, justifyContent: "flex-end", position: "relative" }}>
                <Button variant="ghost" size="sm" icon="download" onClick={() => window.WBToast("Downloading " + f.name)} />
                <div style={{ position: "relative" }} onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="sm" icon="ellipsis" onClick={() => setMenu(menu === f.name ? null : f.name)} />
                  {menu === f.name && <RowMenu file={f} onClose={() => setMenu(null)} />}
                </div>
              </div>
            </div>
          ))}
        </Card>

        {/* Upload modal */}
        <Modal open={upload} onClose={() => setUpload(false)} icon="upload" title="Upload Document" subtitle="Add a file to the repository."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setUpload(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { setUpload(false); window.WBToast("Document uploaded"); }}>Upload</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ border: "2px dashed var(--border-strong)", borderRadius: "var(--radius-lg)", padding: "36px 24px", textAlign: "center", background: "var(--cream-50)" }}>
              <span className="wb-ico" style={{ width: 32, height: 32, color: "var(--text-muted)", display: "inline-flex" }}><i data-lucide="cloud-upload"></i></span>
              <div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)", marginTop: 10 }}>Drag &amp; drop a file here</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 4 }}>or click to browse · PDF, JPG, PNG up to 20 MB</div>
            </div>
            <Select label="Folder" options={FOLDERS.map((f) => f.name)} />
            <Select label="Property" options={["Portfolio-wide", ...window.WB_SITES]} />
          </div>
        </Modal>
      </div>
    );
  }
  window.DocumentsScreen = DocumentsScreen;
})();
