// Documents page — file manager + platform documents (contracts, guides)
// Two tabs: "My Files" (customer uploads via Supabase Storage) and
// "Platform Documents" (admin-published templates: contracts, manuals, guides)

const { useState: useStateDoc, useEffect: useEffectDoc, useRef: useRefDoc, useCallback: useCallbackDoc } = React;

const DOC_ICON = `M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8`;
const UPLOAD_ICON = `M12 21V7 M5 12l7-7 7 7 M3 3h18`;
const DOWNLOAD_ICON = `M12 3v14 M5 12l7 7 7-7 M3 21h18`;
const TRASH_ICON = `M3 6h18 M8 6V4h8v2 M19 6l-1 14H6L5 6`;
const FOLDER_ICON = `M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2z`;
const SEARCH_ICON = `M11 19a8 8 0 100-16 8 8 0 000 16z M21 21l-4.3-4.3`;
const X_ICON = `M6 6l12 12 M6 18L18 6`;
const CHECK_ICON = `M5 12l5 5L20 7`;
const EYE_ICON = `M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z M12 9a3 3 0 100 6 3 3 0 000-6z`;

const Ico = ({ d, size = 16, stroke = "currentColor", fill = "none", sw = 1.6 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={stroke}
    strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
    {typeof d === "string" ? <path d={d} /> : d}
  </svg>
);

const FILE_CATEGORIES = [
  { k: "all",       l: "All files" },
  { k: "financial", l: "Financial" },
  { k: "board",     l: "Board & Investor" },
  { k: "contracts", l: "Contracts" },
  { k: "tax",       l: "Tax & Compliance" },
  { k: "other",     l: "Other" },
];

const DOC_CATEGORIES = [
  { k: "all",        l: "All" },
  { k: "onboarding", l: "Onboarding" },
  { k: "contract",   l: "Contracts" },
  { k: "manual",     l: "Manuals" },
  { k: "policy",     l: "Policies" },
  { k: "guide",      l: "Guides" },
];

// ── Mime type → display label + colour ──────────────────────────────────────
function mimeLabel(mime = "") {
  if (mime.includes("pdf"))        return { label: "PDF",   color: "#ef4444" };
  if (mime.includes("spreadsheet") || mime.includes("excel") || mime.includes("csv"))
                                   return { label: "XLSX",  color: "#16a34a" };
  if (mime.includes("word") || mime.includes("document"))
                                   return { label: "DOCX",  color: "#2563eb" };
  if (mime.includes("presentation") || mime.includes("powerpoint"))
                                   return { label: "PPTX",  color: "#d97706" };
  if (mime.includes("image"))      return { label: "IMG",   color: "#8b5cf6" };
  if (mime.includes("text"))       return { label: "TXT",   color: "#6b7280" };
  return { label: "FILE", color: "#6b7280" };
}

function fmtBytes(bytes) {
  if (!bytes) return "—";
  if (bytes < 1024)       return bytes + " B";
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
  return (bytes / (1024 * 1024)).toFixed(1) + " MB";
}

function fmtDate(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

// ── File badge ───────────────────────────────────────────────────────────────
function FileBadge({ mime, size = 36 }) {
  const { label, color } = mimeLabel(mime);
  return (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: color + "18", border: `1px solid ${color}30`,
      display: "flex", alignItems: "center", justifyContent: "center",
      flexShrink: 0,
    }}>
      <span style={{ fontSize: size * 0.26, fontWeight: 700, color, letterSpacing: -0.5 }}>{label}</span>
    </div>
  );
}

// ── Upload drop zone ─────────────────────────────────────────────────────────
function UploadZone({ onFiles, uploading }) {
  const [dragging, setDragging] = useStateDoc(false);
  const inputRef = useRefDoc(null);

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    const files = Array.from(e.dataTransfer.files);
    if (files.length) onFiles(files);
  };

  return (
    <div
      onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
      onDragLeave={() => setDragging(false)}
      onDrop={handleDrop}
      onClick={() => inputRef.current?.click()}
      style={{
        border: `2px dashed ${dragging ? "var(--accent)" : "var(--border)"}`,
        borderRadius: 12,
        padding: "32px 24px",
        textAlign: "center",
        cursor: uploading ? "not-allowed" : "pointer",
        background: dragging ? "var(--accent)08" : "var(--surface-2)",
        transition: "all 0.15s",
        marginBottom: 24,
        opacity: uploading ? 0.6 : 1,
      }}
    >
      <input
        ref={inputRef}
        type="file"
        multiple
        accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.txt,.png,.jpg,.jpeg,.gif,.webp"
        style={{ display: "none" }}
        onChange={(e) => { const f = Array.from(e.target.files || []); if (f.length) onFiles(f); e.target.value = ""; }}
        disabled={uploading}
      />
      <div style={{ marginBottom: 8 }}>
        <Ico d={UPLOAD_ICON} size={28} stroke={dragging ? "var(--accent)" : "var(--text-3)"} sw={1.5} />
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-1)", marginBottom: 4 }}>
        {uploading ? "Uploading…" : "Drop files here or click to upload"}
      </div>
      <div style={{ fontSize: 12, color: "var(--text-3)" }}>
        PDF, Word, Excel, PowerPoint, CSV, images — up to 50 MB each
      </div>
    </div>
  );
}

// ── Upload modal ─────────────────────────────────────────────────────────────
function UploadModal({ files, onSubmit, onCancel, uploading }) {
  const [metas, setMetas] = useStateDoc(() =>
    files.map(f => ({ category: "other", description: "" }))
  );

  const update = (i, key, val) =>
    setMetas(m => m.map((x, idx) => idx === i ? { ...x, [key]: val } : x));

  return (
    <div className="pc-modal-backdrop" onClick={onCancel}>
      <div className="pc-modal" style={{ maxWidth: 560 }} onClick={e => e.stopPropagation()}>
        <div className="pc-modal-hd">
          <div style={{ fontSize: 15, fontWeight: 600 }}>Upload {files.length} file{files.length > 1 ? "s" : ""}</div>
          <button className="pc-icon-btn" onClick={onCancel}><Ico d={X_ICON} size={14} /></button>
        </div>
        <div className="pc-modal-body" style={{ maxHeight: 420, overflowY: "auto" }}>
          {files.map((f, i) => (
            <div key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 16, paddingBottom: 16, borderBottom: i < files.length - 1 ? "1px solid var(--border)" : "none" }}>
              <FileBadge mime={f.type} size={40} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-1)", marginBottom: 6, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.name}</div>
                <div style={{ display: "flex", gap: 8, marginBottom: 6 }}>
                  <select
                    value={metas[i].category}
                    onChange={e => update(i, "category", e.target.value)}
                    className="pc-input"
                    style={{ fontSize: 12, padding: "4px 8px", flex: "0 0 160px" }}
                  >
                    {FILE_CATEGORIES.filter(c => c.k !== "all").map(c => (
                      <option key={c.k} value={c.k}>{c.l}</option>
                    ))}
                  </select>
                  <span style={{ fontSize: 11, color: "var(--text-3)", alignSelf: "center" }}>{fmtBytes(f.size)}</span>
                </div>
                <input
                  type="text"
                  placeholder="Optional description…"
                  value={metas[i].description}
                  onChange={e => update(i, "description", e.target.value)}
                  className="pc-input"
                  style={{ fontSize: 12, padding: "4px 8px", width: "100%" }}
                />
              </div>
            </div>
          ))}
        </div>
        <div className="pc-modal-ft">
          <button className="pc-btn ghost" onClick={onCancel} disabled={uploading}>Cancel</button>
          <button className="pc-btn primary" onClick={() => onSubmit(metas)} disabled={uploading}>
            {uploading ? "Uploading…" : `Upload ${files.length} file${files.length > 1 ? "s" : ""}`}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── My Files tab ─────────────────────────────────────────────────────────────
function MyFilesTab({ companyId }) {
  const [files, setFiles] = useStateDoc([]);
  const [loading, setLoading] = useStateDoc(true);
  const [catFilter, setCatFilter] = useStateDoc("all");
  const [search, setSearch] = useStateDoc("");
  const [pendingUpload, setPendingUpload] = useStateDoc(null); // files selected, waiting for metadata
  const [uploading, setUploading] = useStateDoc(false);
  const [deleting, setDeleting] = useStateDoc(null);
  const [notice, setNotice] = useStateDoc(null);

  const showNotice = (msg, type = "success") => {
    setNotice({ msg, type });
    setTimeout(() => setNotice(null), 4000);
  };

  const loadFiles = useCallbackDoc(async () => {
    if (!companyId) return;
    setLoading(true);
    const db = window.supabaseClient;
    const { data, error } = await db
      .from("company_files")
      .select("*")
      .eq("company_id", companyId)
      .order("created_at", { ascending: false });
    if (!error) setFiles(data || []);
    setLoading(false);
  }, [companyId]);

  useEffectDoc(() => { loadFiles(); }, [loadFiles]);

  const handleUpload = async (metas) => {
    if (!companyId || !pendingUpload) return;
    setUploading(true);
    const db = window.supabaseClient;
    const { data: { user } } = await db.auth.getUser();
    let successCount = 0;

    for (let i = 0; i < pendingUpload.length; i++) {
      const file = pendingUpload[i];
      const meta = metas[i];
      const ext = file.name.split(".").pop() || "bin";
      const fileId = crypto.randomUUID();
      const storagePath = `${companyId}/${fileId}.${ext}`;

      // Upload to Supabase Storage
      const { error: upErr } = await db.storage
        .from("company-documents")
        .upload(storagePath, file, { contentType: file.type, upsert: false });

      if (upErr) {
        console.error("Upload error for", file.name, upErr.message);
        continue;
      }

      // Insert DB record
      const { error: dbErr } = await db.from("company_files").insert({
        company_id: companyId,
        uploaded_by: user.id,
        name: file.name,
        storage_path: storagePath,
        size_bytes: file.size,
        mime_type: file.type || "application/octet-stream",
        category: meta.category,
        description: meta.description || null,
      });

      if (!dbErr) successCount++;
    }

    setUploading(false);
    setPendingUpload(null);
    await loadFiles();
    if (successCount > 0) {
      showNotice(`${successCount} file${successCount > 1 ? "s" : ""} uploaded successfully.`);
    } else {
      showNotice("Upload failed. Please try again.", "error");
    }
  };

  const handleDownload = async (file) => {
    const db = window.supabaseClient;
    const { data, error } = await db.storage
      .from("company-documents")
      .createSignedUrl(file.storage_path, 120); // 2 min expiry
    if (error || !data?.signedUrl) {
      showNotice("Could not generate download link.", "error");
      return;
    }
    const a = document.createElement("a");
    a.href = data.signedUrl;
    a.download = file.name;
    a.click();
  };

  const handleDelete = async (file) => {
    setDeleting(file.id);
    const db = window.supabaseClient;
    // Delete from storage
    await db.storage.from("company-documents").remove([file.storage_path]);
    // Delete DB record
    const { error } = await db.from("company_files").delete().eq("id", file.id);
    if (!error) {
      setFiles(f => f.filter(x => x.id !== file.id));
      showNotice("File deleted.");
    } else {
      showNotice("Delete failed.", "error");
    }
    setDeleting(null);
  };

  const filtered = files.filter(f => {
    if (catFilter !== "all" && f.category !== catFilter) return false;
    if (search && !f.name.toLowerCase().includes(search.toLowerCase()) &&
        !(f.description || "").toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div>
      {/* Notice */}
      {notice && (
        <div style={{
          padding: "10px 14px", borderRadius: 8, marginBottom: 16, fontSize: 13,
          background: notice.type === "error" ? "var(--danger)15" : "var(--success)15",
          color: notice.type === "error" ? "var(--danger)" : "var(--success)",
          border: `1px solid ${notice.type === "error" ? "var(--danger)" : "var(--success)"}30`,
          display: "flex", alignItems: "center", gap: 8,
        }}>
          <Ico d={notice.type === "error" ? X_ICON : CHECK_ICON} size={14} />
          {notice.msg}
        </div>
      )}

      {/* Upload zone */}
      <UploadZone onFiles={setPendingUpload} uploading={uploading} />

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ position: "relative", flex: "0 0 220px" }}>
          <Ico d={SEARCH_ICON} size={14} stroke="var(--text-3)" style={{ position: "absolute", left: 9, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }} />
          <input
            type="text"
            placeholder="Search files…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="pc-input"
            style={{ paddingLeft: 30, fontSize: 13, width: "100%" }}
          />
        </div>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {FILE_CATEGORIES.map(c => (
            <button
              key={c.k}
              className={`pc-btn-mini ${catFilter === c.k ? "primary" : "ghost"}`}
              onClick={() => setCatFilter(c.k)}
            >{c.l}</button>
          ))}
        </div>
        <div style={{ marginLeft: "auto", fontSize: 12, color: "var(--text-3)" }}>
          {filtered.length} file{filtered.length !== 1 ? "s" : ""}
        </div>
      </div>

      {/* File list */}
      {loading ? (
        <div style={{ textAlign: "center", padding: 40, color: "var(--text-3)" }}>Loading…</div>
      ) : filtered.length === 0 ? (
        <div style={{ textAlign: "center", padding: 48, color: "var(--text-3)" }}>
          <Ico d={FOLDER_ICON} size={36} stroke="var(--text-4)" sw={1.2} />
          <div style={{ marginTop: 12, fontSize: 14, fontWeight: 500 }}>
            {files.length === 0 ? "No files uploaded yet" : "No files match your filter"}
          </div>
          <div style={{ marginTop: 4, fontSize: 12, color: "var(--text-4)" }}>
            {files.length === 0 ? "Drag and drop files above to get started." : "Try clearing the search or filter."}
          </div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {filtered.map(file => (
            <div key={file.id} style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "10px 12px", borderRadius: 8,
              background: "var(--surface-2)",
              border: "1px solid var(--border)",
              transition: "background 0.12s",
            }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--surface-3)"}
              onMouseLeave={e => e.currentTarget.style.background = "var(--surface-2)"}
            >
              <FileBadge mime={file.mime_type} size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {file.name}
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 2, display: "flex", gap: 10 }}>
                  <span>{fmtBytes(file.size_bytes)}</span>
                  <span>{FILE_CATEGORIES.find(c => c.k === file.category)?.l || file.category}</span>
                  <span>{fmtDate(file.created_at)}</span>
                  {file.description && <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 200 }}>{file.description}</span>}
                </div>
              </div>
              <div style={{ display: "flex", gap: 4, flexShrink: 0 }}>
                <button
                  className="pc-icon-btn"
                  title="Download"
                  onClick={() => handleDownload(file)}
                  style={{ padding: 6 }}
                >
                  <Ico d={DOWNLOAD_ICON} size={14} />
                </button>
                <button
                  className="pc-icon-btn"
                  title="Delete"
                  onClick={() => handleDelete(file)}
                  disabled={deleting === file.id}
                  style={{ padding: 6, color: deleting === file.id ? "var(--text-4)" : "var(--danger)" }}
                >
                  <Ico d={TRASH_ICON} size={14} stroke={deleting === file.id ? "var(--text-4)" : "var(--danger)"} />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Upload modal */}
      {pendingUpload && !uploading && (
        <UploadModal
          files={pendingUpload}
          onSubmit={handleUpload}
          onCancel={() => setPendingUpload(null)}
          uploading={uploading}
        />
      )}
    </div>
  );
}

// ── Platform Documents tab ───────────────────────────────────────────────────
function PlatformDocsTab({ companyProfile }) {
  const [docs, setDocs] = useStateDoc([]);
  const [loading, setLoading] = useStateDoc(true);
  const [catFilter, setCatFilter] = useStateDoc("all");
  const [viewing, setViewing] = useStateDoc(null);

  useEffectDoc(() => {
    const db = window.supabaseClient;
    if (!db) return;
    (async () => {
      // Fetch published company-specific docs
      let query = db.from("company_documents")
        .select("*, document_templates(name, slug, category)")
        .in("status", ["published", "signed"]);

      if (companyProfile?.id) {
        query = query.eq("company_id", companyProfile.id);
      }

      const { data: compDocs } = await query.order("created_at", { ascending: false });

      // Fetch global platform templates (active, no company restriction)
      const { data: templates } = await db
        .from("document_templates")
        .select("*")
        .eq("is_active", true)
        .order("sort_order", { ascending: true });

      const allDocs = [
        ...(compDocs || []).map(d => ({
          ...d,
          _source: "company",
          _category: d.category,
          _name: d.name,
        })),
        ...(templates || [])
          .filter(t => {
            const companyDocIds = (compDocs || []).map(d => d.template_id);
            return !companyDocIds.includes(t.id);
          })
          .map(t => ({
            id: t.id,
            name: t.name,
            category: t.category,
            body_html: substituteVars(t.body_html, companyProfile),
            status: "published",
            created_at: t.created_at,
            _source: "template",
            _category: t.category,
            _name: t.name,
          })),
      ];

      setDocs(allDocs);
      setLoading(false);
    })();
  }, [companyProfile?.id]);

  const filtered = catFilter === "all" ? docs : docs.filter(d => d._category === catFilter);

  const CATEGORY_COLORS = {
    contract: { bg: "#2563eb18", color: "#2563eb" },
    manual:   { bg: "#16a34a18", color: "#16a34a" },
    policy:   { bg: "#d9770618", color: "#d97706" },
    guide:    { bg: "#059669_18", color: "#059669", bg2: "#05966918" },
    onboarding: { bg: "#0891b218", color: "#0891b2" },
  };

  const getCat = (cat) => CATEGORY_COLORS[cat] || { bg: "var(--surface-3)", color: "var(--text-3)" };

  if (viewing) {
    return (
      <div>
        <button className="pc-btn ghost" style={{ marginBottom: 16 }} onClick={() => setViewing(null)}>
          ← Back to documents
        </button>
        <div style={{
          background: "var(--surface-2)", borderRadius: 12,
          border: "1px solid var(--border)", padding: "32px 40px",
          maxWidth: 760,
        }}>
          <div style={{
            fontSize: 11, textTransform: "uppercase", letterSpacing: 0.8,
            color: "var(--text-3)", marginBottom: 8,
          }}>
            {viewing._category}
          </div>
          {viewing.signed_at && (
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              fontSize: 12, color: "var(--success)", background: "var(--success)15",
              borderRadius: 6, padding: "4px 10px", marginBottom: 16,
            }}>
              <Ico d={CHECK_ICON} size={12} stroke="var(--success)" />
              Acknowledged {fmtDate(viewing.signed_at)}
            </div>
          )}
          <div
            className="pc-doc-body"
            style={{ fontSize: 14, lineHeight: 1.8, color: "var(--text-1)" }}
            dangerouslySetInnerHTML={{ __html: viewing.body_html }}
          />
          {viewing.status === "published" && !viewing.signed_at && viewing._source === "company" && (
            <div style={{ marginTop: 32, paddingTop: 24, borderTop: "1px solid var(--border)" }}>
              <AcknowledgeButton doc={viewing} onAcknowledged={(d) => {
                setDocs(prev => prev.map(x => x.id === d.id ? { ...x, ...d, signed_at: d.signed_at } : x));
                setViewing(v => ({ ...v, signed_at: d.signed_at }));
              }} />
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: "flex", gap: 6, marginBottom: 20, flexWrap: "wrap" }}>
        {DOC_CATEGORIES.map(c => (
          <button
            key={c.k}
            className={`pc-btn-mini ${catFilter === c.k ? "primary" : "ghost"}`}
            onClick={() => setCatFilter(c.k)}
          >{c.l}</button>
        ))}
      </div>

      {loading ? (
        <div style={{ textAlign: "center", padding: 40, color: "var(--text-3)" }}>Loading…</div>
      ) : filtered.length === 0 ? (
        <div style={{ textAlign: "center", padding: 48, color: "var(--text-3)" }}>
          <Ico d={DOC_ICON} size={36} stroke="var(--text-4)" sw={1.2} />
          <div style={{ marginTop: 12, fontSize: 14 }}>No documents in this category</div>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
          {filtered.map(doc => {
            const catStyle = getCat(doc._category);
            return (
              <div
                key={doc.id}
                onClick={() => setViewing(doc)}
                style={{
                  padding: "16px 18px", borderRadius: 10, cursor: "pointer",
                  background: "var(--surface-2)", border: "1px solid var(--border)",
                  transition: "all 0.15s",
                }}
                onMouseEnter={e => { e.currentTarget.style.background = "var(--surface-3)"; e.currentTarget.style.borderColor = "var(--accent)50"; }}
                onMouseLeave={e => { e.currentTarget.style.background = "var(--surface-2)"; e.currentTarget.style.borderColor = "var(--border)"; }}
              >
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8, marginBottom: 8 }}>
                  <div style={{
                    fontSize: 11, fontWeight: 600, textTransform: "uppercase",
                    letterSpacing: 0.6, padding: "2px 8px", borderRadius: 4,
                    background: catStyle.bg, color: catStyle.color,
                  }}>
                    {doc._category}
                  </div>
                  {doc.signed_at && (
                    <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 11, color: "var(--success)" }}>
                      <Ico d={CHECK_ICON} size={11} stroke="var(--success)" />
                      Signed
                    </div>
                  )}
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-1)", marginBottom: 6, lineHeight: 1.3 }}>
                  {doc._name}
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", display: "flex", alignItems: "center", gap: 6 }}>
                  <Ico d={EYE_ICON} size={12} stroke="var(--text-4)" />
                  Click to read
                  {doc.status === "published" && !doc.signed_at && doc._source === "company" && (
                    <span style={{ marginLeft: 4, color: "var(--warning)", fontWeight: 500 }}>· Action required</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── Acknowledge button ────────────────────────────────────────────────────────
function AcknowledgeButton({ doc, onAcknowledged }) {
  const [loading, setLoading] = useStateDoc(false);

  const handleAck = async () => {
    setLoading(true);
    const db = window.supabaseClient;
    const { data: { user } } = await db.auth.getUser();
    const now = new Date().toISOString();
    const { error } = await db.from("company_documents").update({
      status: "signed",
      signed_at: now,
      signed_by_user_id: user?.id,
    }).eq("id", doc.id);
    setLoading(false);
    if (!error) onAcknowledged({ ...doc, status: "signed", signed_at: now });
  };

  return (
    <button className="pc-btn primary" onClick={handleAck} disabled={loading}>
      {loading ? "Saving…" : "Acknowledge & Accept"}
    </button>
  );
}

// ── Variable substitution for template rendering ──────────────────────────────
function substituteVars(html = "", profile = {}) {
  if (!html) return "";
  const now = new Date();
  const vars = {
    company_name:       profile?.name || "Your Company",
    company_legal_name: profile?.name || "Your Company",
    owner_name:         profile?.owner_name || "Valued Client",
    plan_name:          profile?.plan || "Starter",
    start_date:         now.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }),
    monthly_fee:        "$49/month",
    support_hours:      "Monday–Friday 9am–6pm ET",
    brand_name:         "Perdura Capital",
    support_email:      "support@perdura.com",
  };
  return html.replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k] || `{{${k}}}`);
}

// ── Main DocumentsPage ───────────────────────────────────────────────────────
function DocumentsPage({ companyProfile, scopedCompanyId }) {
  const [tab, setTab] = useStateDoc("files");
  const [companyId, setCompanyId] = useStateDoc(scopedCompanyId || companyProfile?.id || null);

  useEffectDoc(() => {
    if (companyId) return;
    const db = window.supabaseClient;
    if (!db) return;
    (async () => {
      const { data: { user } } = await db.auth.getUser();
      if (!user) return;
      const { data: m } = await db.from("company_users").select("company_id")
        .eq("user_id", user.id).eq("status", "Active").maybeSingle();
      if (m?.company_id) setCompanyId(m.company_id);
    })();
  }, []);

  return (
    <div className="pc-page">
      <div className="pc-page-hd">
        <div>
          <h1 className="pc-page-title">Documents</h1>
          <p className="pc-page-sub">Your uploaded files and platform documents — contracts, guides, and policies.</p>
        </div>
      </div>

      <div className="pc-section-tabs" style={{ marginBottom: 24 }}>
        <button className={tab === "files" ? "active" : ""} onClick={() => setTab("files")}>
          My Files
        </button>
        <button className={tab === "platform" ? "active" : ""} onClick={() => setTab("platform")}>
          Platform Documents
        </button>
      </div>

      {tab === "files" && <MyFilesTab companyId={companyId} />}
      {tab === "platform" && <PlatformDocsTab companyProfile={companyProfile} />}

      <style>{`
        .pc-doc-body h1 { font-size: 22px; font-weight: 700; margin: 0 0 16px; color: var(--text-1); }
        .pc-doc-body h2 { font-size: 16px; font-weight: 600; margin: 24px 0 8px; color: var(--text-1); }
        .pc-doc-body p  { margin: 0 0 12px; color: var(--text-2); }
        .pc-doc-body ul, .pc-doc-body ol { margin: 0 0 12px; padding-left: 20px; color: var(--text-2); }
        .pc-doc-body li { margin-bottom: 4px; }
        .pc-doc-body strong { color: var(--text-1); }
      `}</style>
    </div>
  );
}
