/* =====================================================================
   DOC VIEW — renders GLRDOCS structured model as styled HTML.
   <DocBody> = the rendered "paper"; <DocPreviewModal> = fullscreen reader.
   ===================================================================== */
function fileGlyph(t) {
  return t === "XLSX" ? "grid" : "doc";
}
function fileColor(t) {
  return t === "XLSX" ? "var(--avail)" : "var(--navy)";
}

/* watermark overlay tiles */
function Watermark({ name }) {
  const text = ((name || "Confidential").toUpperCase() + " · CONFIDENTIAL");
  return (
    <div aria-hidden="true" style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none", zIndex: 2 }}>
      <div style={{ position: "absolute", top: "-20%", left: "-20%", width: "140%", height: "140%", transform: "rotate(-28deg)", display: "flex", flexDirection: "column", gap: 64, opacity: 0.06 }}>
        {Array.from({ length: 9 }).map((_, r) => (
          <div key={r} style={{ whiteSpace: "nowrap", fontWeight: 800, fontSize: 22, letterSpacing: 2, color: "var(--navy)", textAlign: "center" }}>
            {Array.from({ length: 4 }).map((_, c) => <span key={c} style={{ marginRight: 80 }}>{text}</span>)}
          </div>
        ))}
      </div>
    </div>
  );
}

/* the rendered document content (paper sheet) */
function DocBody({ doc, watermark, compact }) {
  if (!doc) return null;
  const pad = compact ? 20 : 56;
  if (doc.kind === "sheet") {
    return (
      <div style={{ position: "relative", background: "#fff", padding: pad }}>
        <Watermark name={watermark} />
        <div style={{ position: "relative", zIndex: 1 }}>
          <DocHeader doc={doc} compact={compact} />
          {doc.sheets.map((sh, si) => (
            <div key={si} style={{ marginTop: 18 }}>
              {doc.sheets.length > 1 && <div className="label" style={{ marginBottom: 8 }}>{sh.name}</div>}
              <div style={{ overflowX: "auto", border: "1px solid var(--line)", borderRadius: 4 }}>
                <table className="docsheet">
                  <thead>
                    <tr>{sh.cols.map((c, i) => <th key={i} className={(sh.money || []).includes(i) || (sh.int || []).includes(i) ? "num" : ""}>{c}</th>)}</tr>
                  </thead>
                  <tbody>
                    {sh.rows.map((r, ri) => {
                      const isTotal = sh.total && String(r[1] || r[0]).includes(sh.total);
                      const isVac = String(r[1] || "").toLowerCase().includes("vacant");
                      return (
                        <tr key={ri} className={isTotal ? "tot" : ""} style={isVac ? { color: "var(--slate-2)", fontStyle: "italic" } : null}>
                          {r.map((cell, ci) => {
                            const isMoney = (sh.money || []).includes(ci);
                            const isInt = (sh.int || []).includes(ci);
                            let v = cell;
                            if (typeof cell === "number") {
                              if (isMoney) v = (cell < 0 ? "(" + Math.abs(cell).toLocaleString() + ")" : "$" + cell.toLocaleString());
                              else if (isInt) v = cell.toLocaleString();
                              else v = cell.toLocaleString();
                            }
                            return <td key={ci} className={(isMoney || isInt || typeof cell === "number") ? "num tnum" : ""}>{v}</td>;
                          })}
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              {sh.note && <p className="xsmall muted" style={{ marginTop: 8 }}>{sh.note}</p>}
            </div>
          ))}
          <DocFoot />
        </div>
      </div>
    );
  }
  // document
  return (
    <div style={{ position: "relative", background: "#fff", padding: pad }}>
      <Watermark name={watermark} />
      <div style={{ position: "relative", zIndex: 1, maxWidth: compact ? "none" : 660, margin: "0 auto" }}>
        <DocHeader doc={doc} compact={compact} />
        {(doc.blocks || []).map((b, i) => <Block key={i} b={b} compact={compact} />)}
        <DocFoot />
      </div>
    </div>
  );
}

function DocHeader({ doc, compact }) {
  return (
    <div>
      <div className="eyebrow brass" style={{ fontSize: 10 }}>Great Lakes Realty</div>
      <h1 style={{ fontSize: compact ? 20 : 27, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 8, color: "var(--ink)", lineHeight: 1.1 }}>{doc.title}</h1>
      {doc.subtitle && <p className="muted" style={{ marginTop: 5, fontSize: compact ? 12.5 : 14 }}>{doc.subtitle}</p>}
      <div className="brass-rule" style={{ marginTop: 14 }} />
    </div>
  );
}
function DocFoot() {
  return (
    <div style={{ marginTop: 26, paddingTop: 12, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", color: "var(--slate-2)", fontSize: 10.5 }}>
      <span>GREAT LAKES REALTY · CONFIDENTIAL — Do not distribute</span>
      <span>Information deemed reliable but not guaranteed</span>
    </div>
  );
}

function Block({ b, compact }) {
  if (b.t === "h") return <h2 style={{ fontSize: compact ? 14 : 16, fontWeight: 700, color: "var(--navy)", marginTop: 22, letterSpacing: "-0.01em" }}>{b.text}</h2>;
  if (b.t === "tagline") return <p style={{ fontStyle: "italic", color: "var(--ink-2)", fontSize: compact ? 14 : 16, marginTop: 14, lineHeight: 1.5 }}>{b.text}</p>;
  if (b.t === "p") return <p style={{ marginTop: 10, fontSize: compact ? 13 : 14.5, color: "var(--ink)", lineHeight: 1.62 }}>{b.text}</p>;
  if (b.t === "note") return <p style={{ marginTop: 10, fontSize: compact ? 11.5 : 12.5, color: "var(--slate)", fontStyle: "italic", lineHeight: 1.5 }}>{b.text}</p>;
  if (b.t === "bul") return (
    <ul style={{ marginTop: 12, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
      {(b.items || []).map((it, i) => (
        <li key={i} style={{ display: "flex", gap: 11, fontSize: compact ? 13 : 14.5, color: "var(--ink)", lineHeight: 1.5 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--brass)", flex: "none", marginTop: 7 }} />
          <span>{it}</span>
        </li>
      ))}
    </ul>
  );
  if (b.t === "kv") return (
    <div style={{ marginTop: 14, border: "1px solid var(--line)", borderRadius: 4 }}>
      {(b.rows || []).map(([k, v], i) => (
        <div key={i} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "9px 14px", borderTop: i ? "1px solid var(--line)" : "none" }}>
          <span className="small muted">{k}</span>
          <span className="small b6 tnum" style={{ textAlign: "right" }}>{v}</span>
        </div>
      ))}
    </div>
  );
  if (b.t === "table") {
    const align = b.align || b.cols.map((_, i) => (i === 0 ? 0 : 1));
    return (
      <div style={{ marginTop: 16, overflowX: "auto", border: "1px solid var(--line)", borderRadius: 4 }}>
        <table className="docsheet">
          <thead><tr>{b.cols.map((c, i) => <th key={i} className={align[i] ? "num" : ""}>{c}</th>)}</tr></thead>
          <tbody>
            {(b.rows || []).map((r, ri) => {
              const emph = (b.emphasize || []).includes(r[0]);
              const blank = r.slice(1).every((c) => c === "");
              return (
                <tr key={ri} className={emph ? "tot" : ""} style={blank ? { background: "var(--paper-2)" } : null}>
                  {r.map((cell, ci) => <td key={ci} className={align[ci] ? "num tnum" : ""} style={emph ? { fontWeight: 700 } : null}>{cell}</td>)}
                </tr>
              );
            })}
          </tbody>
        </table>
        {b.note && <p className="xsmall muted" style={{ padding: "8px 12px", margin: 0 }}>{b.note}</p>}
      </div>
    );
  }
  if (b.t === "sign") return (
    <div style={{ marginTop: 26 }}>
      <div style={{ width: 170, height: 1, background: "var(--line-2)" }} />
      <div className="small b6" style={{ marginTop: 12 }}>{b.role || "Great Lakes Realty"}</div>
      <div className="xsmall muted" style={{ marginTop: 3 }}>Generated {new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}</div>
    </div>
  );
  return null;
}

/* fullscreen reader */
function DocPreviewModal({ file, listing, me, onClose }) {
  const doc = useMemo(() => (file ? window.GLRDOCS.build(file, listing) : null), [file, listing]);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);
  if (!file) return null;
  return ReactDOM.createPortal((
    <div className="docmodal-scrim" onClick={onClose}>
      <div className="docmodal" onClick={(e) => e.stopPropagation()}>
        <div className="docmodal-bar">
          <div className="row gap10 ac" style={{ minWidth: 0 }}>
            <Icon name={fileGlyph(file.t)} size={17} style={{ color: "#cdd9e6", flex: "none" }} />
            <span className="b6" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.n}</span>
            <span className="tag" style={{ background: "rgba(255,255,255,0.1)", color: "#cdd9e6", flex: "none" }}>{file.t} · {file.s}</span>
          </div>
          <div className="row gap8 ac">
            <button className="btn brass sm" onClick={() => { window.GLR.downloadFile(file, listing, me.name).then(() => showToast("Download token issued \u2014 logged")).catch((e) => showToast(e.message || "Download failed")); }}><Icon name="download" size={15} /> Download</button>
            <button className="btn ghost sm docmodal-x" onClick={onClose}><Icon name="x" size={16} /></button>
          </div>
        </div>
        <div className="docmodal-scroll scroll-y">
          <div className="docpaper">
            <DocBody doc={doc} watermark={me.name} />
          </div>
        </div>
      </div>
    </div>
  ), document.body);
}

Object.assign(window, { DocBody, DocPreviewModal, Watermark, fileGlyph, fileColor });
