/* ============================================================
   beedle dataroom — document content renderers
   Self-contained mock surfaces (no external assets)
   ============================================================ */

// ---------- primitives ----------
function Letterhead({ doc, kicker }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "2px solid #14242E", paddingBottom: 16, marginBottom: 26 }}>
      <div>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase", color: "#7E8E94" }}>{kicker || "beedle solutions inc."}</div>
        <div style={{ fontFamily: "var(--serif)", fontSize: 26, fontWeight: 500, letterSpacing: "-.01em", marginTop: 4 }}>{doc.name}</div>
      </div>
      <Brand size={22} />
    </div>
  );
}
function Para({ w = ["100%"], lh = 12, gap = 9, color = "#C9D2D6" }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap }}>
      {w.map((width, i) => <div key={i} style={{ height: lh, width, background: color, borderRadius: 3 }} />)}
    </div>
  );
}
function H({ children }) { return <div style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 600, margin: "22px 0 10px", color: "#14242E" }}>{children}</div>; }

// SVG bar chart
function BarChart({ data, color = "#15B4E7", h = 150, labels }) {
  const max = Math.max(...data);
  const bw = 100 / data.length;
  return (
    <svg viewBox={`0 0 100 ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: h }}>
      {data.map((v, i) => {
        const bh = (v / max) * (h - 22);
        return <rect key={i} x={i * bw + bw * 0.22} y={h - 18 - bh} width={bw * 0.56} height={bh} rx="1.5" fill={i === data.length - 1 ? color : shade(color, 30)} />;
      })}
      {labels && labels.map((l, i) => (
        <text key={i} x={i * bw + bw * 0.5} y={h - 5} fontSize="4.4" fill="#7E8E94" textAnchor="middle" fontFamily="var(--sans)">{l}</text>
      ))}
    </svg>
  );
}
// SVG line chart
function LineChart({ data, color = "#1E9E6A", h = 150 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => [i * (100 / (data.length - 1)), h - 16 - ((v - min) / (max - min || 1)) * (h - 30)]);
  const d = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = d + ` L100 ${h - 16} L0 ${h - 16} Z`;
  return (
    <svg viewBox={`0 0 100 ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: h }}>
      <defs><linearGradient id={"lg" + color.slice(1)} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor={color} stopOpacity=".22" /><stop offset="1" stopColor={color} stopOpacity="0" />
      </linearGradient></defs>
      <path d={area} fill={`url(#lg${color.slice(1)})`} />
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="1.6" fill={color} />)}
    </svg>
  );
}
function KPI({ label, value, sub, tone = "#15B4E7" }) {
  return (
    <div style={{ border: "1px solid #E9E4D9", borderRadius: 14, padding: "16px 18px", background: "#fff" }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: "#7E8E94", letterSpacing: ".02em" }}>{label}</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 30, fontWeight: 500, color: "#14242E", marginTop: 4, letterSpacing: "-.01em" }}>{value}</div>
      {sub && <div style={{ fontSize: 12, fontWeight: 600, color: tone, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// ---------- HTML documents ----------
function ExecSummary() {
  return (
    <div className="paper-doc"><div className="pd-pad">
      <div className="eyebrow" style={{ color: "#0E97C6" }}>Executive Summary</div>
      <h1 style={{ fontFamily: "var(--serif)", fontWeight: 430, fontSize: 32, lineHeight: 1.12, letterSpacing: "-.015em", margin: "10px 0 8px" }}>
        Technology that keeps families close — without the friction.
      </h1>
      <p style={{ fontSize: 15.5, color: "#42565F", lineHeight: 1.7, margin: "0 0 18px" }}>
        beedle is an always-on care hub built for the 54 million North Americans aging at home, and the families who worry about them. A large-format touchscreen with voice assistance lets a loved one answer a video call with a single “yes” — while caregivers manage everything remotely from a simple web dashboard.
      </p>
      <H>The problem</H>
      <p style={{ fontSize: 14.5, color: "#42565F", lineHeight: 1.7, margin: 0 }}>
        Mainstream devices assume dexterity, memory and confidence that many seniors don’t have. The result is isolation for them and anxiety for their families. Existing “senior tech” is either a medical alert pendant or a locked-down tablet — neither creates connection.
      </p>
      <H>Our solution</H>
      <p style={{ fontSize: 14.5, color: "#42565F", lineHeight: 1.7, margin: 0 }}>
        One device, three jobs: effortless communication, gentle daily structure, and quiet safety. Photos, music and reminders fill the screen between calls; caregivers get presence and anomaly signals without surveillance.
      </p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, margin: "24px 0 6px" }}>
        <KPI label="Active homes" value="2,140" sub="+38% QoQ" />
        <KPI label="Net revenue retention" value="118%" sub="trailing 12-mo" tone="#1E9E6A" />
        <KPI label="Family NPS" value="71" sub="best-in-class" tone="#E0762B" />
      </div>
      <p style={{ fontSize: 13, color: "#7E8E94", marginTop: 22 }}>Prepared for Series A diligence · Confidential · May 2026</p>
    </div></div>
  );
}
function TractionDoc() {
  return (
    <div className="paper-doc"><div className="pd-pad">
      <Letterhead doc={{ name: "Traction Dashboard" }} kicker="KPI Snapshot · Jun 2026" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
        <KPI label="MRR" value="$214K" sub="+22% MoM" />
        <KPI label="Active homes" value="2,140" sub="+38% QoQ" tone="#1E9E6A" />
        <KPI label="Logo retention" value="96%" sub="annual" tone="#E0762B" />
        <KPI label="Pilots (care orgs)" value="11" sub="3 converting" tone="#7A57D1" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 22, marginTop: 26 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: "#42565F", marginBottom: 8 }}>Monthly recurring revenue</div>
          <LineChart data={[42, 58, 65, 79, 96, 118, 140, 162, 178, 214]} color="#15B4E7" />
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: "#42565F", marginBottom: 8 }}>New homes / month</div>
          <BarChart data={[120, 165, 190, 240, 300, 360]} labels={["J", "F", "M", "A", "M", "J"]} color="#1E9E6A" />
        </div>
      </div>
      <H>Cohort retention</H>
      <p style={{ fontSize: 14, color: "#42565F", lineHeight: 1.7, margin: 0 }}>
        The 2025 install base retains above 96% annually. Expansion comes from multi-device households and care-home seat growth, driving net revenue retention to 118%.
      </p>
    </div></div>
  );
}
function UnitEconDoc() {
  return (
    <div className="paper-doc"><div className="pd-pad">
      <Letterhead doc={{ name: "Unit Economics" }} kicker="Confidential · May 2026" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12 }}>
        <KPI label="Blended CAC" value="$310" />
        <KPI label="Lifetime value" value="$2,940" sub="9.5× CAC" tone="#1E9E6A" />
        <KPI label="Payback" value="7.2 mo" tone="#E0762B" />
      </div>
      <H>Contribution margin by channel</H>
      <BarChart data={[58, 64, 71, 49]} labels={["Direct", "Care orgs", "Referral", "Retail"]} color="#7A57D1" h={140} />
      <p style={{ fontSize: 14, color: "#42565F", lineHeight: 1.7, marginTop: 16 }}>
        Hardware is sold near cost; margin accrues on the recurring care subscription ($39/mo). Care-organization seats carry the strongest contribution and the lowest CAC.
      </p>
    </div></div>
  );
}
function FoundersDoc() {
  const team = [
    ["Dana Whitfield", "Co-founder & CEO", "DW", "#15B4E7", "Ex-product lead in connected health. Built beedle after caring for a grandparent with dementia."],
    ["Aiden Cho", "Co-founder & CTO", "AC", "#1E9E6A", "Embedded + voice systems. Previously shipped accessibility hardware at scale."],
    ["Renée Dubois", "VP Finance", "RD", "#E0762B", "Two-time startup CFO; led a prior Series B and exit."],
    ["Sofia Marchetti", "Head of Product", "SM", "#7A57D1", "Designs for cognitive accessibility; ex-care-tech and museum interaction design."],
  ];
  return (
    <div className="paper-doc"><div className="pd-pad">
      <Letterhead doc={{ name: "Founders & Leadership" }} kicker="The team" />
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {team.map((m, i) => (
          <div key={i} style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
            <span style={{ width: 52, height: 52, borderRadius: "50%", flex: "none", display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 17, background: `linear-gradient(150deg,${m[3]},${shade(m[3], -20)})` }}>{m[2]}</span>
            <div>
              <div style={{ fontWeight: 700, fontSize: 16 }}>{m[0]}</div>
              <div style={{ fontSize: 13, color: "#0E97C6", fontWeight: 600, marginBottom: 4 }}>{m[1]}</div>
              <div style={{ fontSize: 13.5, color: "#42565F", lineHeight: 1.6, maxWidth: "58ch" }}>{m[4]}</div>
            </div>
          </div>
        ))}
      </div>
    </div></div>
  );
}

// ---------- PDF (paper) docs ----------
function PdfDoc({ doc, page }) {
  // financial / chart-bearing docs
  const charts = {
    "Market & TAM Analysis": <BarChart data={[18, 34, 52, 78]} labels={["’24", "’26", "’28", "’30"]} color="#1E9E6A" />,
    "P&L Statement 2024–2025": <BarChart data={[0.6, 1.1, 1.9, 2.7]} labels={["Q1", "Q2", "Q3", "Q4"]} color="#E0762B" />,
    "Financial Model (5-yr)": <LineChart data={[1.2, 3.4, 7.1, 13.8, 24.6]} color="#15B4E7" />,
  };
  const chart = charts[doc.name];
  return (
    <div className="paper-doc"><div className="pd-pad">
      <Letterhead doc={doc} kicker={doc.by ? "Author · " + doc.by : undefined} />
      <Para w={["96%", "100%", "88%"]} />
      <div style={{ height: 14 }} />
      <Para w={["100%", "92%"]} />
      {chart && (<><H>{doc.name.includes("Market") ? "Serviceable market ($B)" : doc.name.includes("Model") ? "Net revenue projection ($M)" : "Quarterly revenue ($M)"}</H>{chart}</>)}
      <H>Notes</H>
      <Para w={["100%", "97%", "84%", "70%"]} />
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 34, paddingTop: 14, borderTop: "1px solid #E9E4D9", fontSize: 11.5, color: "#A9B4B7" }}>
        <span>beedle solutions inc. — confidential</span><span>Page {page} of {doc.pages}</span>
      </div>
    </div></div>
  );
}

// ---------- Image docs ----------
function ImageDoc({ doc, page }) {
  if (doc.name.startsWith("Org")) {
    const box = (t, s, c) => (
      <div style={{ border: "1px solid #E9E4D9", borderRadius: 10, padding: "10px 14px", background: "#fff", textAlign: "center", minWidth: 120 }}>
        <div style={{ fontWeight: 700, fontSize: 13 }}>{t}</div><div style={{ fontSize: 11, color: c }}>{s}</div>
      </div>
    );
    return (
      <div className="img-doc" style={{ background: "#fff", padding: 40, width: 720, maxWidth: "100%" }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 22 }}>{box("Dana Whitfield", "CEO", "#0E97C6")}</div>
        <div style={{ display: "flex", justifyContent: "center", gap: 18, marginBottom: 22 }}>
          {box("Aiden Cho", "CTO", "#1E9E6A")}{box("Renée Dubois", "Finance", "#E0762B")}{box("Sofia Marchetti", "Product", "#7A57D1")}
        </div>
        <div style={{ display: "flex", justifyContent: "center", gap: 12 }}>
          {["Engineering ×6", "Care Ops ×4", "GTM ×3", "Design ×2"].map(t => box(t, "", "#7E8E94"))}
        </div>
      </div>
    );
  }
  // device photography — stylized product render
  const tints = ["#16314a", "#1d4a63", "#0E97C6", "#15B4E7", "#2a5a72", "#13405a"];
  const t = tints[(page - 1) % tints.length];
  return (
    <div className="img-doc" style={{ width: 760, maxWidth: "100%", aspectRatio: "4/3", background: `radial-gradient(120% 90% at 70% 20%, ${shade(t, 34)}, ${t})`, display: "grid", placeItems: "center", position: "relative" }}>
      {/* a beedle device silhouette */}
      <div style={{ width: "46%", aspectRatio: "16/10", background: "#0c1620", borderRadius: 14, border: "6px solid #07101a", boxShadow: "0 30px 70px -20px rgba(0,0,0,.6)", position: "relative", display: "grid", placeItems: "center" }}>
        <div style={{ position: "absolute", inset: 10, borderRadius: 8, background: "linear-gradient(150deg,#16B4E7,#0E8FBE)", display: "grid", placeItems: "center" }}>
          <Brand size={26} />
        </div>
      </div>
      <div style={{ position: "absolute", bottom: 16, left: 18, color: "rgba(255,255,255,.8)", fontSize: 12, fontWeight: 600 }}>beedle 24″ hub · {page} / {doc.pages}</div>
    </div>
  );
}

// ---------- Video doc ----------
function VideoDoc({ doc }) {
  const [playing, setPlaying] = React.useState(false);
  return (
    <div className="video-doc">
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 100% at 30% 20%, rgba(21,180,231,.4), transparent 60%)" }} />
      <button onClick={() => setPlaying(p => !p)} style={{ position: "relative", width: 78, height: 78, borderRadius: "50%", border: "0", background: "rgba(255,255,255,.94)", display: "grid", placeItems: "center", cursor: "pointer", boxShadow: "0 14px 40px -8px rgba(0,0,0,.5)" }}>
        <Icon name={playing ? "clock" : "play"} size={30} style={{ color: "#14242E", marginLeft: playing ? 0 : 4 }} />
      </button>
      <div style={{ position: "absolute", left: 24, right: 24, bottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, color: "#fff" }}>
          <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{playing ? "0:32" : "0:00"}</span>
          <div style={{ flex: 1, height: 4, borderRadius: 99, background: "rgba(255,255,255,.25)" }}>
            <div style={{ width: playing ? "14%" : "0%", height: "100%", borderRadius: 99, background: "#15B4E7", transition: "width .6s" }} />
          </div>
          <span style={{ fontSize: 13, fontWeight: 600, opacity: .8, fontVariantNumeric: "tabular-nums" }}>{doc.duration}</span>
        </div>
        <div style={{ color: "rgba(255,255,255,.7)", fontSize: 12.5, marginTop: 10 }}>{doc.name} — 1080p · captions available</div>
      </div>
    </div>
  );
}

// ---------- PPT deck ----------
function PptDoc({ doc }) {
  const slides = [
    { t: "beedle", s: "Simplified technology for families & seniors", cover: true },
    { t: "The problem", s: "54M aging at home. Mainstream tech excludes them." },
    { t: "The product", s: "One screen. Three jobs: connect, structure, safety." },
    { t: "Traction", s: "2,140 homes · $214K MRR · 118% NRR", chart: [40, 60, 82, 110, 140, 214] },
    { t: "Market", s: "$48B aging-in-place opportunity by 2030" },
    { t: "The ask", s: "Raising $6M Series A to scale care-org channel" },
  ];
  const [cur, setCur] = React.useState(0);
  const sl = slides[cur];
  return (
    <div className="ppt-doc">
      <div className="ppt-main">
        {sl.cover ? (
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(150deg,#16B4E7,#0B6E94)", display: "grid", placeItems: "center", flexDirection: "column", gap: 14 }}>
            <Brand size={64} light />
            <div style={{ color: "rgba(255,255,255,.9)", fontSize: 18, fontFamily: "var(--serif)" }}>{sl.s}</div>
          </div>
        ) : (
          <div style={{ position: "absolute", inset: 0, padding: "44px 52px", display: "flex", flexDirection: "column" }}>
            <div className="eyebrow" style={{ color: "#0E97C6" }}>beedle · series a</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 38, fontWeight: 500, letterSpacing: "-.015em", marginTop: 8 }}>{sl.t}</div>
            <div style={{ fontSize: 18, color: "#42565F", marginTop: 8, maxWidth: "40ch", lineHeight: 1.5 }}>{sl.s}</div>
            {sl.chart && <div style={{ marginTop: "auto" }}><BarChart data={sl.chart} color="#15B4E7" h={120} /></div>}
            <div style={{ marginTop: "auto", alignSelf: "flex-end", color: "#A9B4B7", fontSize: 12, fontWeight: 600 }}>{cur + 1} / {slides.length}</div>
          </div>
        )}
      </div>
      <div className="ppt-rail scroll">
        {slides.map((s, i) => (
          <button key={i} className={"ppt-thumb" + (i === cur ? " on" : "")} onClick={() => setCur(i)}>
            <div style={{ width: "100%", height: "100%", display: "grid", placeItems: "center", background: s.cover ? "linear-gradient(150deg,#16B4E7,#0B6E94)" : "#fff", fontSize: 8, color: s.cover ? "#fff" : "#42565F", fontWeight: 700, padding: 4, textAlign: "center" }}>
              {s.cover ? "beedle" : s.t}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ---------- real uploaded files (streamed from the backend) ----------
function FileCard({ doc, url }) {
  return (
    <div className="paper-doc"><div className="pd-pad" style={{ textAlign: "center", padding: "64px 40px" }}>
      <div style={{ width: 72, height: 72, borderRadius: 18, margin: "0 auto 18px", display: "grid", placeItems: "center", background: "linear-gradient(150deg,#15B4E7,#0E97C6)", color: "#fff" }}>
        <Icon name="file" size={32} />
      </div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 500, marginBottom: 6 }}>{doc.name}</div>
      <div style={{ fontSize: 13.5, color: "#7E8E94", marginBottom: 20 }}>{doc.type.toUpperCase()} · {doc.size}</div>
      <p style={{ fontSize: 14, color: "#42565F", maxWidth: "46ch", margin: "0 auto 22px", lineHeight: 1.6 }}>
        {T("This file type can’t be previewed inline. Open it in a new tab to view the original.")}
      </p>
      <a className="btn btn-primary" href={url} target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "inline-flex" }}>
        <Icon name="eye" size={16} />{T("Open in new tab")}
      </a>
    </div></div>
  );
}

function RealFileDoc({ doc }) {
  const url = api.rawUrl(doc.id);
  if (doc.type === "pdf" || doc.type === "html") {
    return (
      <div className="paper-doc" style={{ width: "100%", background: "#fff", padding: 0, overflow: "hidden" }}>
        <iframe src={url} title={doc.name} style={{ width: "100%", height: "80vh", border: 0, display: "block" }} />
      </div>
    );
  }
  if (doc.type === "image") {
    return (
      <div className="img-doc" style={{ display: "grid", placeItems: "center", background: "#0c1620", padding: 24, minHeight: "60vh" }}>
        <img src={url} alt={doc.name} style={{ maxWidth: "100%", maxHeight: "80vh", borderRadius: 10, boxShadow: "0 24px 60px -20px rgba(0,0,0,.6)" }} />
      </div>
    );
  }
  if (doc.type === "video") {
    return (
      <div className="video-doc" style={{ display: "grid", placeItems: "center", background: "#000", minHeight: "60vh" }}>
        <video src={url} controls style={{ maxWidth: "100%", maxHeight: "80vh", borderRadius: 10 }} />
      </div>
    );
  }
  return <FileCard doc={doc} url={url} />;
}

// Admin-authored HTML page: sanitise (doc profile) + token the asset srcs, then
// render. richHtml re-sanitises on every render, so stored junk can't reach the DOM.
function HtmlDoc({ doc }) {
  return (
    <div className="paper-doc"><div className="pd-pad">
      <div className="htmldoc" dangerouslySetInnerHTML={{ __html: withAssetTokens(richHtml(doc.html, "doc")) }} />
    </div></div>
  );
}

// ---------- router ----------
function DocContent({ doc, page }) {
  if (doc.hasFile) return <RealFileDoc doc={doc} />;
  if (doc.type === "html") {
    if (!isEmptyHtml(doc.html)) return <HtmlDoc doc={doc} />;     // authored page
    if (doc.name.startsWith("Executive")) return <ExecSummary />;
    if (doc.name.startsWith("Traction")) return <TractionDoc />;
    if (doc.name.startsWith("Unit")) return <UnitEconDoc />;
    if (doc.name.startsWith("Founders")) return <FoundersDoc />;
    return <ExecSummary />;
  }
  if (doc.type === "pdf") return <PdfDoc doc={doc} page={page} />;
  if (doc.type === "image") return <ImageDoc doc={doc} page={page} />;
  if (doc.type === "video") return <VideoDoc doc={doc} />;
  if (doc.type === "ppt") return <PptDoc doc={doc} />;
  return null;
}

Object.assign(window, { DocContent, BarChart, LineChart, KPI });
