/* Wood OS — Central de Arquivos + Visualizador de Anexos */
const { useState: useStateFiles, useMemo: useMemoFiles, useEffect: useEffectFiles } = React;

/* ============================================================
   File kind meta
   ============================================================ */
const FILE_KIND_META = {
  image: { label: "Imagem",   color: "#A78BFA", icon: "eye" },
  pdf:   { label: "PDF",      color: "#EF4444", icon: "file-text" },
  dwg:   { label: "CAD",      color: "#38BDF8", icon: "ruler" },
  other: { label: "Outro",    color: "#737373", icon: "file" },
};

const ENTITY_META = {
  cliente:     { label: "Cliente",     icon: "users",    color: "#34D399" },
  obra:        { label: "Obra",        icon: "hammer",   color: "#F59E0B" },
  orcamento:   { label: "Orçamento",   icon: "dollar",   color: "#38BDF8" },
  solicitacao: { label: "Solicitação", icon: "inbox",    color: "#A78BFA" },
  geral:       { label: "Geral",       icon: "boxes",    color: "#737373" },
};

const TONE_GRADIENTS = {
  "from-emerald-700 to-emerald-900":  "linear-gradient(135deg, #047857, #022C22)",
  "from-emerald-600 to-teal-900":     "linear-gradient(135deg, #059669, #134E4A)",
  "from-amber-600 to-amber-900":      "linear-gradient(135deg, #B45309, #78350F)",
  "from-amber-700 to-orange-900":     "linear-gradient(135deg, #B45309, #7C2D12)",
  "from-orange-700 to-red-900":       "linear-gradient(135deg, #C2410C, #7F1D1D)",
  "from-purple-700 to-indigo-900":    "linear-gradient(135deg, #6D28D9, #312E81)",
  "from-cyan-700 to-blue-900":        "linear-gradient(135deg, #0E7490, #1E3A8A)",
  "from-blue-700 to-indigo-900":      "linear-gradient(135deg, #1D4ED8, #312E81)",
  "from-pink-700 to-rose-900":        "linear-gradient(135deg, #BE185D, #881337)",
  "from-slate-700 to-slate-900":      "linear-gradient(135deg, #334155, #0F172A)",
};

/* ============================================================
   FilesPage — Central de Arquivos
   ============================================================ */
const FilesPage = ({ navigate }) => {
  const [kind, setKind] = useStateFiles("todos");
  const [entityType, setEntityType] = useStateFiles("todos");
  const [q, setQ] = useStateFiles("");
  const [view, setView] = useStateFiles("grid");
  const [preview, setPreview] = useStateFiles(null);
  const [uploading, setUploading] = useStateFiles(false);

  const files = MOCK.files;

  const filtered = useMemoFiles(() => files.filter(f => {
    if (kind !== "todos" && f.kind !== kind) return false;
    if (entityType !== "todos" && f.entityType !== entityType) return false;
    if (q && !`${f.name} ${f.entityName} ${f.category}`.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  }), [files, kind, entityType, q]);

  const metrics = useMemoFiles(() => {
    const byKind = {};
    files.forEach(f => { byKind[f.kind] = (byKind[f.kind] || 0) + 1; });
    // estimate space — convert "1.2 MB" / "612 KB" to bytes
    const parseSize = (s) => {
      const m = s.match(/^([\d.]+)\s*(KB|MB|GB)$/i);
      if (!m) return 0;
      const v = parseFloat(m[1]);
      return v * { KB: 1024, MB: 1024 * 1024, GB: 1024 * 1024 * 1024 }[m[2].toUpperCase()];
    };
    const totalBytes = files.reduce((s, f) => s + parseSize(f.size), 0);
    const totalMB = totalBytes / (1024 * 1024);
    const recent = files.filter(f => daysUntil(f.uploadedAt) >= -7).length;
    return { total: files.length, byKind, totalMB, recent };
  }, [files]);

  return (
    <>
      <PageHeader
        kicker="Sistema"
        title="Central de Arquivos"
        subtitle="Todos os anexos do sistema em um só lugar. Visualize sem baixar, busque por nome ou obra, filtre por tipo."
        actions={
          <>
            <div className="iflex items-center" style={{ background: "var(--wood-surface-2)", border: "1px solid var(--wood-border)", borderRadius: 10, padding: 2 }}>
              <button onClick={() => setView("grid")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "grid" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "grid" ? "var(--cream)" : undefined }}>
                <Icon name="layers" size={13} /> Grade
              </button>
              <button onClick={() => setView("list")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "list" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "list" ? "var(--cream)" : undefined }}>
                <Icon name="log" size={13} /> Lista
              </button>
            </div>
            <button className="wood-btn wood-btn-primary" onClick={() => setUploading(true)}><Icon name="paperclip" size={13} /> Enviar arquivo</button>
          </>
        }
      />

      <FormModal open={uploading} onClose={() => setUploading(false)}
        kicker="NOVO ARQUIVO" title="Enviar arquivo" icon="paperclip"
        submitLabel="Enviar" maxWidth={560}
        footerHint="Suporta imagens (JPG, PNG), PDF, DWG, planilhas e mais. Limite de 25 MB por arquivo.">
        <div className="rounded-lg p-8 text-center cursor-pointer" style={{ background: "rgba(0,0,0,0.18)", border: "1.5px dashed var(--wood-border-strong)" }}>
          <Icon name="paperclip" size={24} className="text-3 mx-auto mb-2" />
          <div className="text-sm" style={{ fontWeight: 500 }}>Arraste arquivos aqui ou clique para selecionar</div>
          <div className="text-xs text-4 mt-1">PDF, DWG, JPG, PNG, XLSX · até 25 MB cada</div>
        </div>
        <FormGrid>
          <FormRow label="Vincular a">
            <select className="wood-select">
              <option value="geral">Geral (sem vínculo)</option>
              <option value="cliente">Cliente</option>
              <option value="obra">Obra</option>
              <option value="orcamento">Orçamento</option>
              <option value="solicitacao">Solicitação</option>
            </select>
          </FormRow>
          <FormRow label="Categoria">
            <select className="wood-select">
              <option>Contrato</option><option>Documento</option><option>Projeto técnico</option>
              <option>Memorial</option><option>Referência</option><option>Progresso</option>
              <option>Amostras</option><option>Manual</option><option>Cronograma</option>
            </select>
          </FormRow>
        </FormGrid>
        <FormRow label="Visibilidade">
          <select className="wood-select">
            <option value="interno">Interno (somente equipe)</option>
            <option value="cliente">Visível ao cliente (Portal)</option>
            <option value="publico">Público (link compartilhável)</option>
          </select>
        </FormRow>
      </FormModal>

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-5">
        <MetricCard icon="file" label="Arquivos" value={metrics.total} sub={`${metrics.recent} novos esta semana`} accent="amber" delay={0} />
        <MetricCard icon="eye" label="Imagens" value={metrics.byKind.image || 0} sub="fotos de progresso" accent="info" delay={60} />
        <MetricCard icon="file-text" label="PDFs" value={metrics.byKind.pdf || 0} sub="contratos, memoriais, orçamentos" accent="warning" delay={120} />
        <MetricCard icon="package" label="Espaço usado" value={`${metrics.totalMB.toFixed(1)} MB`} sub="de 5 GB do plano" accent="success" delay={180} />
      </div>

      {/* Filters */}
      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={kind === "todos"} onClick={() => setKind("todos")} count={files.length}>Todos</FilterChip>
        {Object.entries(FILE_KIND_META).map(([k, m]) => {
          const c = files.filter(f => f.kind === k).length;
          if (c === 0) return null;
          return (
            <FilterChip key={k} active={kind === k} onClick={() => setKind(k)} count={c}>
              <Icon name={m.icon} size={11} style={{ color: m.color, marginRight: 4 }} /> {m.label}
            </FilterChip>
          );
        })}
        <div className="wood-divider md-hide" style={{ width: 1, height: 24, background: "var(--wood-border)" }} />
        <select className="wood-select" value={entityType} onChange={e => setEntityType(e.target.value)} style={{ maxWidth: 180 }}>
          <option value="todos">Todas as entidades</option>
          {Object.entries(ENTITY_META).map(([k, m]) => <option key={k} value={k}>{m.label}</option>)}
        </select>
        <div className="flex items-center gap-2 flex-1" style={{ minWidth: 200 }}>
          <Icon name="search" size={14} className="text-3" />
          <input
            className="flex-1"
            style={{ background: "transparent", border: "none", outline: "none", fontSize: 13, color: "var(--text)" }}
            placeholder="Buscar arquivo, obra ou categoria…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
        </div>
      </div>

      {filtered.length === 0 ? (
        <EmptyState icon="file" title="Nenhum arquivo" description="Ajuste os filtros ou envie um novo arquivo." />
      ) : view === "grid" ? (
        <FilesGrid files={filtered} onOpen={setPreview} />
      ) : (
        <FilesList files={filtered} onOpen={setPreview} />
      )}

      <FilePreviewModal file={preview} onClose={() => setPreview(null)} />
    </>
  );
};

/* ============================================================
   FilesGrid — visual cards with mock thumbnails
   ============================================================ */
const FilesGrid = ({ files, onOpen }) => (
  <div className="grid grid-cols-4 gap-4">
    {files.map((f, i) => {
      const kindMeta = FILE_KIND_META[f.kind] || FILE_KIND_META.other;
      const entMeta = ENTITY_META[f.entityType] || ENTITY_META.geral;
      return (
        <div key={f.id} onClick={() => onOpen(f)}
             className="wood-card wood-card-hover cursor-pointer slide-up overflow-hidden"
             style={{ animationDelay: `${i * 30}ms`, padding: 0 }}>
          {/* Thumbnail */}
          <div style={{
            height: 140, position: "relative",
            background: TONE_GRADIENTS[f.tone] || "linear-gradient(135deg, #1E293B, #0F172A)",
            display: "flex", alignItems: "center", justifyContent: "center"
          }}>
            <FileVisual f={f} />
            <div style={{ position: "absolute", top: 8, left: 8 }}>
              <span className="wood-badge" style={{ background: "rgba(0,0,0,0.55)", backdropFilter: "blur(6px)", color: kindMeta.color, padding: "2px 7px", border: `1px solid ${kindMeta.color}55`, textTransform: "uppercase", fontSize: 9.5, fontWeight: 700 }}>
                {kindMeta.label}
              </span>
            </div>
            {f.pages && (
              <div style={{ position: "absolute", top: 8, right: 8 }}>
                <span className="wood-badge" style={{ background: "rgba(0,0,0,0.55)", backdropFilter: "blur(6px)", color: "var(--text-2)", padding: "2px 7px", fontSize: 10 }}>
                  {f.pages} pág.
                </span>
              </div>
            )}
          </div>
          <div className="p-3">
            <div className="text-sm truncate" style={{ fontWeight: 600 }} title={f.name}>{f.name}</div>
            <div className="text-xs text-3 flex items-center gap-1.5 mt-1 truncate">
              <Icon name={entMeta.icon} size={10} style={{ color: entMeta.color, flexShrink: 0 }} />
              <span className="truncate">{f.entityName}</span>
            </div>
            <div className="flex items-center justify-between mt-2 text-xs text-4">
              <span>{f.size}</span>
              <span>{fmtDate(f.uploadedAt)}</span>
            </div>
          </div>
        </div>
      );
    })}
  </div>
);

/* ============================================================
   FilesList — table view
   ============================================================ */
const FilesList = ({ files, onOpen }) => (
  <div className="wood-card overflow-hidden" style={{ padding: 0 }}>
    <table className="wood-table">
      <thead>
        <tr><th>Arquivo</th><th>Tipo</th><th>Vinculado a</th><th>Categoria</th><th>Tamanho</th><th>Enviado por</th><th>Data</th></tr>
      </thead>
      <tbody>
        {files.map(f => {
          const km = FILE_KIND_META[f.kind] || FILE_KIND_META.other;
          const em = ENTITY_META[f.entityType] || ENTITY_META.geral;
          return (
            <tr key={f.id} onClick={() => onOpen(f)} style={{ cursor: "pointer" }}>
              <td>
                <div className="flex items-center gap-3">
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: `${km.color}14`, color: km.color, border: `1px solid ${km.color}44`, display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name={km.icon} size={14} />
                  </div>
                  <span style={{ fontWeight: 500 }}>{f.name}</span>
                </div>
              </td>
              <td>
                <span className="wood-badge" style={{ background: `${km.color}14`, color: km.color, padding: "2px 7px", textTransform: "uppercase", fontWeight: 600 }}>{km.label}</span>
              </td>
              <td>
                <div className="flex items-center gap-2">
                  <Icon name={em.icon} size={11} style={{ color: em.color }} />
                  <span className="text-sm">{f.entityName}</span>
                </div>
              </td>
              <td className="text-sm text-3">{f.category}</td>
              <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{f.size}</td>
              <td>
                <div className="flex items-center gap-2">
                  <Avatar name={f.uploadedBy} size={22} />
                  <span className="text-sm">{f.uploadedBy.split(" ")[0]}</span>
                </div>
              </td>
              <td className="text-sm text-3">{fmtDate(f.uploadedAt)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

/* ============================================================
   FileVisual — mock thumbnail content based on file kind
   ============================================================ */
const FileVisual = ({ f }) => {
  if (f.kind === "image") {
    return (
      <>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "repeating-linear-gradient(45deg, transparent 0 16px, rgba(255,255,255,0.04) 16px 17px)",
        }} />
        <Icon name="eye" size={32} style={{ color: "rgba(255,255,255,0.65)", filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.4))" }} />
      </>
    );
  }
  if (f.kind === "pdf") {
    // Mini "PDF page" with bars representing text lines
    return (
      <div style={{
        width: 64, height: 84, background: "rgba(255,255,255,0.94)", borderRadius: 4,
        padding: 8, display: "flex", flexDirection: "column", gap: 4,
        boxShadow: "0 8px 20px rgba(0,0,0,0.5)", color: "#111",
        transform: "rotate(-3deg)"
      }}>
        <div style={{ height: 4, background: "#EF4444", width: "60%", borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "100%", marginTop: 4, borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "100%", borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "85%", borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "70%", borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "95%", marginTop: 4, borderRadius: 1 }} />
        <div style={{ height: 2, background: "#888", width: "55%", borderRadius: 1 }} />
      </div>
    );
  }
  if (f.kind === "dwg") {
    // Mini blueprint with lines
    return (
      <svg width="80" height="80" viewBox="0 0 80 80" style={{ filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.5))" }}>
        <rect x="10" y="14" width="60" height="52" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.5" />
        <line x1="10" y1="34" x2="70" y2="34" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
        <line x1="36" y1="14" x2="36" y2="66" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
        <line x1="20" y1="34" x2="20" y2="66" stroke="rgba(255,255,255,0.5)" strokeWidth="0.8" />
        <line x1="52" y1="14" x2="52" y2="34" stroke="rgba(255,255,255,0.5)" strokeWidth="0.8" />
        <text x="14" y="13" fill="rgba(255,255,255,0.5)" fontSize="6">A</text>
        <text x="40" y="13" fill="rgba(255,255,255,0.5)" fontSize="6">B</text>
        <text x="74" y="40" fill="rgba(255,255,255,0.5)" fontSize="6" transform="rotate(90, 74, 40)">C</text>
      </svg>
    );
  }
  return <Icon name="file" size={32} style={{ color: "rgba(255,255,255,0.65)" }} />;
};

/* ============================================================
   FilePreviewModal — full preview overlay
   ============================================================ */
const FilePreviewModal = ({ file, onClose }) => {
  useEffectFiles(() => {
    if (!file) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [file, onClose]);

  if (!file) return null;
  const km = FILE_KIND_META[file.kind] || FILE_KIND_META.other;
  const em = ENTITY_META[file.entityType] || ENTITY_META.geral;

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(0,0,0,0.78)", backdropFilter: "blur(10px)",
      display: "flex", padding: 24
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} className="wood-card slide-up flex"
           style={{ width: "100%", maxWidth: 1280, margin: "auto", padding: 0, maxHeight: "92vh", overflow: "hidden" }}>
        {/* Left: preview canvas */}
        <div style={{
          flex: 1, minWidth: 0, position: "relative",
          background: TONE_GRADIENTS[file.tone] || "linear-gradient(135deg, #1E293B, #0F172A)",
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: 24, minHeight: 480
        }}>
          {/* Close */}
          <button onClick={onClose} className="wood-btn wood-btn-ghost wood-btn-icon-sm" style={{ position: "absolute", top: 12, right: 12, background: "rgba(0,0,0,0.5)", backdropFilter: "blur(6px)" }}>
            <Icon name="x" size={14} />
          </button>

          {/* Big visual */}
          <FilePreviewBig f={file} />

          {/* Bottom toolbar */}
          <div style={{
            position: "absolute", bottom: 12, left: "50%", transform: "translateX(-50%)",
            display: "flex", gap: 8,
            background: "rgba(0,0,0,0.7)", backdropFilter: "blur(12px)",
            border: "1px solid var(--wood-border)", padding: 6, borderRadius: 12
          }}>
            <button className="wood-btn wood-btn-ghost wood-btn-sm"><Icon name="search" size={12} /> Zoom</button>
            <button className="wood-btn wood-btn-ghost wood-btn-sm"><Icon name="external" size={12} /> Baixar</button>
            <button className="wood-btn wood-btn-ghost wood-btn-sm"><Icon name="send" size={12} /> Compartilhar</button>
            <button className="wood-btn wood-btn-ghost wood-btn-sm" style={{ color: "var(--error)" }}><Icon name="trash" size={12} /></button>
          </div>
        </div>

        {/* Right: metadata sidebar */}
        <div style={{ width: 340, flexShrink: 0, padding: 24, overflowY: "auto", borderLeft: "1px solid var(--wood-border)" }}>
          <div className="flex items-center gap-3 mb-4">
            <div style={{ width: 44, height: 44, borderRadius: 11, background: `${km.color}14`, color: km.color, border: `1px solid ${km.color}44`, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name={km.icon} size={20} />
            </div>
            <div className="min-w-0">
              <div className="text-xs uppercase tracking-widest" style={{ color: km.color, fontWeight: 700, fontSize: 10 }}>{km.label}</div>
              <div className="text-md font-semibold tracking-tight truncate">{file.name}</div>
            </div>
          </div>

          {/* Vinculado a */}
          <div className="rounded-lg p-3 mb-3" style={{ background: `${em.color}08`, border: `1px solid ${em.color}33` }}>
            <div className="text-xs uppercase tracking-widest mb-1.5" style={{ color: em.color, fontWeight: 600, fontSize: 10 }}>VINCULADO A</div>
            <div className="flex items-center gap-2">
              <Icon name={em.icon} size={14} style={{ color: em.color }} />
              <div className="flex-1 min-w-0">
                <div className="text-sm" style={{ fontWeight: 600 }}>{file.entityName}</div>
                <div className="text-xs text-3">{em.label} {file.entityId ? `· ${file.entityId}` : ""}</div>
              </div>
            </div>
          </div>

          {/* Metadata rows */}
          <div className="flex flex-col gap-2 mb-4">
            {[
              { label: "Categoria",    value: file.category },
              { label: "Tamanho",      value: file.size },
              { label: "Páginas",      value: file.pages ? `${file.pages} páginas` : null },
              { label: "Enviado por",  value: file.uploadedBy },
              { label: "Data de envio",value: fmtDateLong(file.uploadedAt) },
              { label: "ID",           value: file.id, mono: true },
            ].filter(d => d.value).map(d => (
              <div key={d.label} className="flex items-start justify-between gap-3 py-1.5" style={{ borderBottom: "1px solid var(--wood-border-soft)" }}>
                <span className="text-xs text-4 uppercase tracking-widest" style={{ fontWeight: 500 }}>{d.label}</span>
                <span className="text-sm text-right" style={{ fontWeight: 500, fontFamily: d.mono ? "ui-monospace, monospace" : undefined }}>{d.value}</span>
              </div>
            ))}
          </div>

          {/* Activity */}
          <div className="text-sm font-semibold mb-2">Atividade</div>
          <div className="flex flex-col gap-2">
            {[
              { user: file.uploadedBy, action: "fez upload do arquivo", time: fmtDate(file.uploadedAt) },
              { user: "Sistema",        action: "vinculou ao registro " + (file.entityId || "geral"), time: fmtDate(file.uploadedAt) },
            ].map((a, i) => (
              <div key={i} className="flex items-start gap-2 text-xs">
                <Avatar name={a.user} size={22} />
                <div className="flex-1">
                  <span style={{ fontWeight: 500 }}>{a.user}</span> <span className="text-3">{a.action}</span>
                  <div className="text-4">{a.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   FilePreviewBig — large render of preview per kind
   ============================================================ */
const FilePreviewBig = ({ f }) => {
  if (f.kind === "image") {
    return (
      <div style={{ position: "relative", width: "92%", aspectRatio: "4 / 3", maxHeight: "78vh", borderRadius: 12, overflow: "hidden", background: "rgba(0,0,0,0.25)", border: "1px solid rgba(255,255,255,0.12)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "repeating-linear-gradient(45deg, transparent 0 28px, rgba(255,255,255,0.05) 28px 29px)",
        }} />
        <div className="text-center relative" style={{ padding: 32 }}>
          <Icon name="eye" size={64} style={{ color: "rgba(255,255,255,0.55)", marginBottom: 16, filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.4))" }} />
          <div className="text-md font-semibold tracking-tight mb-1">{f.name}</div>
          <div className="text-xs text-3">Preview de imagem · {f.size}</div>
        </div>
      </div>
    );
  }
  if (f.kind === "pdf") {
    // "Fake" PDF page mockup
    return (
      <div style={{ position: "relative", display: "flex", gap: 12, alignItems: "center" }}>
        {[0, 1, 2].slice(0, Math.min(3, f.pages || 1)).map((i) => (
          <div key={i} style={{
            width: 280, aspectRatio: "0.71 / 1",
            background: "rgba(255,255,255,0.94)", color: "#111",
            borderRadius: 6, padding: 22,
            boxShadow: i === 0 ? "0 20px 40px rgba(0,0,0,0.5)" : "0 10px 20px rgba(0,0,0,0.3)",
            transform: i === 0 ? "scale(1.08)" : i === 1 ? "scale(0.95) translateY(8px)" : "scale(0.85) translateY(16px)",
            opacity: i === 0 ? 1 : 0.65, zIndex: 3 - i
          }}>
            <div style={{ height: 14, background: "#222", width: "70%", borderRadius: 2, marginBottom: 12 }} />
            <div style={{ height: 6, background: "#EF4444", width: "30%", borderRadius: 1, marginBottom: 18 }} />
            <div style={{ height: 4, background: "#888", width: "100%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "94%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "98%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "70%", marginBottom: 14, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "100%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "92%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "88%", marginBottom: 14, borderRadius: 1 }} />
            <div style={{ height: 60, background: "rgba(16,185,129,0.18)", borderRadius: 3, marginBottom: 14 }} />
            <div style={{ height: 4, background: "#888", width: "100%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "80%", marginBottom: 4, borderRadius: 1 }} />
            <div style={{ height: 4, background: "#888", width: "60%", borderRadius: 1 }} />
            <div style={{ position: "absolute", bottom: 12, right: 16, fontSize: 9, color: "#999", fontFamily: "ui-monospace, monospace" }}>{i + 1} / {f.pages || 1}</div>
          </div>
        ))}
      </div>
    );
  }
  if (f.kind === "dwg") {
    // Big blueprint render
    return (
      <div style={{ width: "84%", aspectRatio: "1.4 / 1", borderRadius: 12, padding: 24, background: "rgba(2,44,34,0.6)", border: "1px solid rgba(56,189,248,0.3)" }}>
        <svg width="100%" height="100%" viewBox="0 0 280 200">
          <rect x="20" y="20" width="240" height="160" fill="none" stroke="rgba(56,189,248,0.85)" strokeWidth="1.5" />
          <line x1="20" y1="100" x2="260" y2="100" stroke="rgba(56,189,248,0.55)" strokeWidth="1" />
          <line x1="140" y1="20" x2="140" y2="180" stroke="rgba(56,189,248,0.55)" strokeWidth="1" />
          <line x1="80"  y1="100" x2="80"  y2="180" stroke="rgba(56,189,248,0.4)" strokeWidth="0.8" />
          <line x1="200" y1="20"  x2="200" y2="100" stroke="rgba(56,189,248,0.4)" strokeWidth="0.8" />
          <rect x="40" y="60" width="40" height="30" fill="rgba(56,189,248,0.1)" stroke="rgba(56,189,248,0.6)" strokeWidth="0.8" />
          <rect x="160" y="120" width="80" height="50" fill="rgba(56,189,248,0.08)" stroke="rgba(56,189,248,0.5)" strokeWidth="0.8" />
          <circle cx="160" cy="60" r="14" fill="none" stroke="rgba(56,189,248,0.5)" strokeWidth="0.8" />
          <text x="40" y="14" fill="rgba(56,189,248,0.85)" fontSize="7" fontFamily="ui-monospace, monospace">A</text>
          <text x="140" y="14" fill="rgba(56,189,248,0.85)" fontSize="7" fontFamily="ui-monospace, monospace">B</text>
          <text x="240" y="14" fill="rgba(56,189,248,0.85)" fontSize="7" fontFamily="ui-monospace, monospace">C</text>
          <text x="14" y="60" fill="rgba(56,189,248,0.85)" fontSize="7" fontFamily="ui-monospace, monospace">1</text>
          <text x="14" y="140" fill="rgba(56,189,248,0.85)" fontSize="7" fontFamily="ui-monospace, monospace">2</text>
          {/* Annotation lines */}
          <g stroke="rgba(56,189,248,0.85)" strokeWidth="0.5">
            <line x1="40" y1="56" x2="40" y2="36" />
            <line x1="80" y1="56" x2="80" y2="36" />
            <text x="55" y="42" fill="rgba(56,189,248,0.85)" fontSize="6" fontFamily="ui-monospace, monospace">600mm</text>
          </g>
          <g stroke="rgba(56,189,248,0.85)" strokeWidth="0.5">
            <line x1="84" y1="60" x2="104" y2="60" />
            <line x1="84" y1="90" x2="104" y2="90" />
            <text x="92" y="78" fill="rgba(56,189,248,0.85)" fontSize="6" fontFamily="ui-monospace, monospace" transform="rotate(90, 92, 78)">400mm</text>
          </g>
          <text x="244" y="190" fill="rgba(56,189,248,0.6)" fontSize="6" fontFamily="ui-monospace, monospace" textAnchor="end">AutoCAD .dwg · esc 1:50</text>
        </svg>
      </div>
    );
  }
  return (
    <div className="text-center">
      <Icon name="file" size={64} style={{ color: "rgba(255,255,255,0.55)", marginBottom: 16 }} />
      <div className="text-md font-semibold tracking-tight mb-1">{f.name}</div>
      <div className="text-sm text-3 mb-3">Preview indisponível para este tipo</div>
      <button className="wood-btn wood-btn-primary"><Icon name="external" size={13} /> Baixar para abrir</button>
    </div>
  );
};

/* expose */
Object.assign(window, { FilesPage, FilePreviewModal });
