(() => {
/* global React, Icons, MOCK, toast */
const { useState, useRef, useEffect, useMemo } = React;

/* =========================================================
   CAPTURE — dental image upload with interactive mouth diagram
   ========================================================= */

const POSITIONS = [
  { id: "upper",  label: "Upper Arch", short: "U" },
  { id: "lower",  label: "Lower Arch", short: "L" },
  { id: "front",  label: "Front Bite", short: "F" },
  { id: "left",   label: "Left Bite",  short: "←" },
  { id: "right",  label: "Right Bite", short: "→" },
];

/* Stylized mouth diagram — arch-shaped tooth rows with selectable zones */
function MouthDiagram({ selected, captured, onSelect }) {
  // upper arch teeth positions (semicircle)
  const upper = Array.from({length: 14}, (_, i) => {
    const angle = Math.PI + (i / 13) * Math.PI; // 180° to 360°
    const r = 110;
    const cx = 180, cy = 170;
    return {
      x: cx + r * Math.cos(angle),
      y: cy + r * Math.sin(angle),
      angle,
    };
  });
  const lower = Array.from({length: 14}, (_, i) => {
    const angle = (i / 13) * Math.PI; // 0° to 180°
    const r = 110;
    const cx = 180, cy = 170;
    return {
      x: cx + r * Math.cos(angle),
      y: cy + r * Math.sin(angle),
      angle,
    };
  });

  const zoneStyle = (id) => {
    const isSel = selected === id;
    const isCap = captured.includes(id);
    return {
      fill: isSel ? "rgba(14,138,109,0.20)" : isCap ? "rgba(14,138,109,0.08)" : "transparent",
      stroke: isSel ? "var(--mint)" : isCap ? "var(--mint)" : "transparent",
      strokeWidth: 1.5,
      strokeDasharray: isSel ? "0" : isCap ? "4 3" : "0",
      transition: "fill .25s, stroke .25s",
      cursor: "pointer",
    };
  };

  return (
    <svg viewBox="0 0 360 340" style={{ width: "100%", maxWidth: 460, display: "block" }}>
      <defs>
        <radialGradient id="mouth-bg" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--mint-soft)" stopOpacity="0.5" />
          <stop offset="100%" stopColor="var(--paper-2)" stopOpacity="0" />
        </radialGradient>
      </defs>

      <circle cx="180" cy="170" r="150" fill="url(#mouth-bg)" />

      {/* Upper arch zone (clickable) */}
      <path
        d="M50 170 Q180 30 310 170 Z"
        style={zoneStyle("upper")}
        onClick={() => onSelect("upper")}
      />
      {/* Lower arch zone */}
      <path
        d="M50 170 Q180 310 310 170 Z"
        style={zoneStyle("lower")}
        onClick={() => onSelect("lower")}
      />

      {/* Left bite — left third */}
      <path
        d="M50 170 Q40 100 90 60 L90 280 Q40 240 50 170 Z"
        style={zoneStyle("left")}
        onClick={() => onSelect("left")}
      />
      {/* Right bite — right third */}
      <path
        d="M310 170 Q320 100 270 60 L270 280 Q320 240 310 170 Z"
        style={zoneStyle("right")}
        onClick={() => onSelect("right")}
      />
      {/* Front bite — center */}
      <circle cx="180" cy="170" r="36"
        style={zoneStyle("front")}
        onClick={() => onSelect("front")}
      />

      {/* Upper teeth */}
      {upper.map((t, i) => {
        const isInArea = ["upper","left","right"].includes(selected) || captured.some(c => ["upper","left","right"].includes(c));
        const isFront = i >= 5 && i <= 8;
        const isLeft = i < 5;
        const isRight = i > 8;
        const highlight =
          (selected === "upper") ||
          (selected === "left" && isLeft) ||
          (selected === "right" && isRight) ||
          (selected === "front" && isFront);
        return (
          <g key={`u${i}`} style={{ transition: "transform .3s" }}>
            <rect
              x={t.x - 9} y={t.y - 12} width={18} height={20} rx={6}
              fill={highlight ? "var(--mint)" : "white"}
              stroke={highlight ? "var(--mint-2)" : "var(--line-2)"}
              strokeWidth="1"
              transform={`rotate(${(t.angle * 180/Math.PI) + 90} ${t.x} ${t.y})`}
              style={{ transition: "fill .25s, stroke .25s" }}
            />
          </g>
        );
      })}
      {/* Lower teeth */}
      {lower.map((t, i) => {
        const isFront = i >= 5 && i <= 8;
        const isLeft = i < 5;
        const isRight = i > 8;
        const highlight =
          (selected === "lower") ||
          (selected === "left" && isLeft) ||
          (selected === "right" && isRight) ||
          (selected === "front" && isFront);
        return (
          <g key={`l${i}`}>
            <rect
              x={t.x - 9} y={t.y - 12} width={18} height={20} rx={6}
              fill={highlight ? "var(--mint)" : "white"}
              stroke={highlight ? "var(--mint-2)" : "var(--line-2)"}
              strokeWidth="1"
              transform={`rotate(${(t.angle * 180/Math.PI) + 90} ${t.x} ${t.y})`}
              style={{ transition: "fill .25s, stroke .25s" }}
            />
          </g>
        );
      })}

      {/* Center sparkle */}
      <g opacity="0.6">
        <circle cx="180" cy="170" r="3" fill="var(--mint)" />
      </g>

      {/* Labels around mouth */}
      <text x="180" y="46"  textAnchor="middle" fontSize="10" fill="var(--muted)" letterSpacing="2" style={{ textTransform: "uppercase" }}>UPPER</text>
      <text x="180" y="305" textAnchor="middle" fontSize="10" fill="var(--muted)" letterSpacing="2" style={{ textTransform: "uppercase" }}>LOWER</text>
      <text x="22"  y="174" textAnchor="middle" fontSize="10" fill="var(--muted)" letterSpacing="2" style={{ textTransform: "uppercase" }}>L</text>
      <text x="338" y="174" textAnchor="middle" fontSize="10" fill="var(--muted)" letterSpacing="2" style={{ textTransform: "uppercase" }}>R</text>
    </svg>
  );
}

function ScreenCapture({ go }) {
  const [step, setStep] = useState("lookup"); // lookup | capture
  const [indvid, setIndvid] = useState("");
  const [patient, setPatient] = useState(null);
  const [loading, setLoading] = useState(false);
  const [selectedPos, setSelectedPos] = useState("upper");
  const [captured, setCaptured] = useState([]);  // positions captured this session
  const [previews, setPreviews] = useState({});  // position -> data URL placeholder
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const fileInputRef = useRef();

  const handleLookup = (e, presetId) => {
    e?.preventDefault();
    const id = presetId ?? indvid;
    if (!id) return;
    setLoading(true);
    setTimeout(() => {
      const p = MOCK.patients.find(x => x.id.toLowerCase().includes(id.toLowerCase()))
              || MOCK.patients[0];
      setPatient(p);
      setLoading(false);
      setStep("capture");
      toast(`Loaded ${p.name}`);
    }, 700);
  };

  const onFile = (file) => {
    if (!file || !patient) return;
    setUploading(true);
    setProgress(0);
    const tick = setInterval(() => {
      setProgress(p => {
        if (p >= 100) {
          clearInterval(tick);
          setUploading(false);
          setCaptured(c => c.includes(selectedPos) ? c : [...c, selectedPos]);
          // Read as data url for preview
          const reader = new FileReader();
          reader.onload = (e) => setPreviews(prev => ({ ...prev, [selectedPos]: e.target.result }));
          reader.readAsDataURL(file);
          toast(`Captured · ${POSITIONS.find(x => x.id === selectedPos).label}`);
          // auto-advance to next un-captured position
          const nextPos = POSITIONS.find(pos => !captured.includes(pos.id) && pos.id !== selectedPos);
          if (nextPos) setTimeout(() => setSelectedPos(nextPos.id), 400);
          return 0;
        }
        return p + 8;
      });
    }, 40);
  };

  if (step === "lookup") {
    return (
      <div className="screen" style={{ display: "grid", placeItems: "center", minHeight: "60vh" }}>
        <div style={{ maxWidth: 560, width: "100%" }}>
          <div className="eyebrow" style={{ textAlign: "center" }}>Step 1 of 2</div>
          <h1 className="h-display" style={{ textAlign: "center", fontSize: 44, marginTop: 8 }}>
            Who are we screening <em>today?</em>
          </h1>
          <p className="lede" style={{ textAlign: "center", margin: "12px auto 0" }}>
            Enter the patient's individual ID to pull up their profile and begin capture.
          </p>
          <form onSubmit={handleLookup} className="card" style={{ marginTop: 28, padding: 24, display: "flex", gap: 10, alignItems: "stretch" }}>
            <input
              className="input"
              style={{ flex: 1, fontSize: 16, padding: "14px 18px" }}
              value={indvid}
              onChange={(e) => setIndvid(e.target.value)}
              placeholder="STU-10248 or scan QR"
              autoFocus
            />
            <button type="submit" className="btn btn-mint" style={{ padding: "12px 22px" }} disabled={!indvid || loading}>
              {loading ? <Spinner /> : <>Continue <Icons.ArrowR size={14} /></>}
            </button>
          </form>

          <div className="row" style={{ justifyContent: "center", marginTop: 22, gap: 24, color: "var(--muted)", fontSize: 12.5 }}>
            <span className="row" style={{ gap: 6 }}><Icons.Sparkle size={14} stroke="var(--mint)" /> AI-assisted detection enabled</span>
            <span className="row" style={{ gap: 6 }}><Icons.Cloud size={14} stroke="var(--mint)" /> Direct to encrypted S3</span>
          </div>

          <div style={{ marginTop: 32 }}>
            <div className="eyebrow">Recent</div>
            <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }} className="stagger">
              {MOCK.patients.slice(0, 6).map(p => (
                <button key={p.id} className="card hover" style={{ padding: 12, textAlign: "left", display: "flex", alignItems: "center", gap: 10 }}
                        onClick={() => { setIndvid(p.id); handleLookup(null, p.id); }}>
                  <div style={{
                    width: 30, height: 30, borderRadius: 8,
                    background: "var(--mint-soft)", color: "var(--mint)",
                    display: "grid", placeItems: "center",
                    fontFamily: "var(--font-display)", fontSize: 14
                  }}>{p.name[0]}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--muted-2)" }}>{p.id}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Step 2 — Capture
  const completionPct = Math.round((captured.length / POSITIONS.length) * 100);

  return (
    <div className="screen" style={{ display: "grid", gridTemplateColumns: "320px 1fr 320px", gap: 24, alignItems: "start" }}>
      {/* LEFT — patient card */}
      <aside className="col" style={{ gap: 16 }}>
        <button onClick={() => { setStep("lookup"); setPatient(null); setCaptured([]); setPreviews({}); }}
                className="maglink" style={{ fontSize: 12, color: "var(--muted)", alignSelf: "flex-start" }}>← Different patient</button>
        <div className="card" style={{ padding: 22 }}>
          <div style={{
            width: 64, height: 64, borderRadius: 18,
            background: "linear-gradient(140deg, var(--mint-soft), var(--gold-soft))",
            color: "var(--ink)", display: "grid", placeItems: "center",
            fontFamily: "var(--font-display)", fontSize: 28,
            marginBottom: 14,
          }}>{patient.name[0]}</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1.1 }}>{patient.name}</div>
          <div className="mono" style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 6 }}>{patient.id}</div>

          <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 10, fontSize: 13 }}>
            <Info k="Age"        v={`${patient.age} yrs`} />
            <Info k="Gender"     v={patient.gender === "M" ? "Male" : "Female"} />
            <Info k="Section"    v={`${patient.dept} · ${patient.unit}`} />
            <Info k="Last visit" v="—" />
          </div>

          {patient.flagged && (
            <div style={{
              marginTop: 14, padding: 12, borderRadius: 10,
              background: "var(--coral-soft)", border: "1px solid var(--coral)", borderLeftWidth: 3,
            }}>
              <div style={{ fontSize: 11, color: "var(--coral)", fontWeight: 700, letterSpacing: ".06em" }}>FLAGGED PRIOR CYCLE</div>
              <div style={{ fontSize: 12.5, marginTop: 4, color: "var(--ink-2)" }}>Mild caries · upper molars. Reassess.</div>
            </div>
          )}
        </div>

        <div className="card card-paper" style={{ padding: 16 }}>
          <div className="eyebrow">Progress</div>
          <div className="row" style={{ marginTop: 10, alignItems: "baseline", gap: 4 }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 36, lineHeight: 1 }}>{captured.length}</span>
            <span style={{ color: "var(--muted)", fontSize: 14 }}>/ 5 positions</span>
          </div>
          <div style={{ height: 5, borderRadius: 99, background: "var(--line)", marginTop: 10, overflow: "hidden" }}>
            <div style={{
              width: `${completionPct}%`, height: "100%",
              background: "linear-gradient(90deg, var(--mint-glow), var(--mint))",
              transition: "width .6s cubic-bezier(.2,.8,.2,1)"
            }} />
          </div>
          {captured.length === 5 && (
            <button className="btn btn-mint" style={{ marginTop: 14, width: "100%", justifyContent: "center" }}
                    onClick={() => { toast("Submitted for review · report queued"); go("reports"); }}>
              <Icons.Check size={14} /> Finalize &amp; submit
            </button>
          )}
        </div>
      </aside>

      {/* CENTER — mouth diagram */}
      <div className="card" style={{ padding: 28, textAlign: "center" }}>
        <div className="eyebrow">Tap a zone to capture</div>
        <h2 className="h-section" style={{ marginTop: 6 }}>
          {POSITIONS.find(p => p.id === selectedPos)?.label}
        </h2>

        <div style={{ marginTop: 12, display: "grid", placeItems: "center" }}>
          <MouthDiagram selected={selectedPos} captured={captured} onSelect={setSelectedPos} />
        </div>

        {/* Position chips */}
        <div style={{ display: "flex", justifyContent: "center", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
          {POSITIONS.map(p => {
            const isCap = captured.includes(p.id);
            const isSel = selectedPos === p.id;
            return (
              <button key={p.id} onClick={() => setSelectedPos(p.id)}
                      className="pill"
                      style={{
                        padding: "6px 14px", fontSize: 12.5,
                        background: isSel ? "var(--ink)" : isCap ? "var(--mint-soft)" : "var(--paper-2)",
                        color: isSel ? "var(--paper)" : isCap ? "var(--mint-2)" : "var(--muted)",
                        borderColor: "transparent",
                        cursor: "pointer",
                      }}>
                {isCap && <Icons.Check size={11} sw="2.5" />}
                {p.label}
              </button>
            );
          })}
        </div>

        {/* Capture controls */}
        <div style={{ marginTop: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <button className="btn btn-primary" style={{ padding: "14px 20px", justifyContent: "center" }} onClick={() => fileInputRef.current?.click()} disabled={uploading}>
            <Icons.Camera size={16} /> {uploading ? "Uploading…" : "Capture reading"}
          </button>
          <button className="btn btn-ghost" style={{ padding: "14px 20px", justifyContent: "center" }} onClick={() => fileInputRef.current?.click()} disabled={uploading}>
            <Icons.Image size={16} /> Upload from gallery
          </button>
        </div>
        <input ref={fileInputRef} type="file" accept="image/*" style={{ display: "none" }}
               onChange={(e) => onFile(e.target.files?.[0])} />

        {uploading && (
          <div style={{ marginTop: 16 }}>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 11.5, color: "var(--muted)" }}>
              <span>Uploading to S3…</span>
              <span className="mono">{progress}%</span>
            </div>
            <div style={{ height: 4, borderRadius: 99, background: "var(--paper-2)", marginTop: 6, overflow: "hidden" }}>
              <div style={{ width: `${progress}%`, height: "100%", background: "var(--mint)", transition: "width .1s linear" }} />
            </div>
          </div>
        )}
      </div>

      {/* RIGHT — captured tiles */}
      <aside className="col" style={{ gap: 12 }}>
        <div className="eyebrow" style={{ paddingLeft: 4 }}>Captured this session</div>
        <div className="stagger" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {POSITIONS.map((p) => {
            const isCap = captured.includes(p.id);
            const preview = previews[p.id];
            return (
              <div key={p.id} onClick={() => setSelectedPos(p.id)} style={{
                position: "relative", borderRadius: 12,
                aspectRatio: "1 / 1",
                background: isCap ? "var(--ink)" : "var(--paper-2)",
                border: "1px solid var(--line)",
                overflow: "hidden", cursor: "pointer",
                transition: "border-color .18s",
              }}>
                {preview ? (
                  <img src={preview} alt={p.label} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                ) : (
                  <div style={{
                    width: "100%", height: "100%", display: "grid", placeItems: "center",
                    color: isCap ? "var(--mint-glow)" : "var(--muted-2)",
                  }}>
                    {isCap ? <Icons.Check size={20} /> : <Icons.Camera size={18} />}
                  </div>
                )}
                <div style={{
                  position: "absolute", left: 6, bottom: 6,
                  background: "rgba(13,22,20,0.7)", color: "var(--paper)",
                  fontSize: 10, padding: "2px 6px", borderRadius: 4,
                  backdropFilter: "blur(4px)",
                }}>{p.label}</div>
              </div>
            );
          })}
        </div>

        <div className="card card-ink" style={{ padding: 16, marginTop: 4 }}>
          <div className="row" style={{ gap: 8 }}>
            <Icons.Sparkle size={14} stroke="var(--mint-glow)" />
            <span className="eyebrow" style={{ color: "rgba(246,241,231,0.55)" }}>AI quality check</span>
          </div>
          <div style={{ fontSize: 12.5, color: "rgba(246,241,231,0.85)", marginTop: 8, lineHeight: 1.5 }}>
            Each capture is auto-checked for focus, framing, and lighting before reaching the dentist.
          </div>
        </div>
      </aside>
    </div>
  );
}

function Info({ k, v }) {
  return (
    <div className="row" style={{ justifyContent: "space-between" }}>
      <span style={{ color: "var(--muted)", fontSize: 12 }}>{k}</span>
      <span style={{ fontWeight: 600, fontSize: 13 }}>{v}</span>
    </div>
  );
}

function Spinner() {
  return (
    <span style={{
      display: "inline-block",
      width: 16, height: 16, borderRadius: 99,
      border: "2px solid currentColor", borderTopColor: "transparent",
      animation: "spin 1s linear infinite",
    }}>
      <style>{`@keyframes spin{to{transform:rotate(360deg);}}`}</style>
    </span>
  );
}

window.ScreenCapture = ScreenCapture;

/* =========================================================
   REPORTS — PDF upload & review
   ========================================================= */

function ScreenReports({ go }) {
  const [tab, setTab] = useState("pending");
  const [dragOver, setDragOver] = useState(false);
  const [search, setSearch] = useState("");

  const pending = MOCK.patients.filter(p => p.captures > 0 && !p.pdf);
  const delivered = MOCK.patients.filter(p => p.pdf);
  const items = tab === "pending" ? pending : delivered;

  const [selected, setSelected] = useState(pending[0]?.id || null);
  const sel = MOCK.patients.find(p => p.id === selected);

  const filtered = items.filter(p =>
    !search || p.name.toLowerCase().includes(search.toLowerCase()) || p.id.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="screen col" style={{ gap: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div className="eyebrow">{pending.length} pending · {delivered.length} delivered</div>
          <h1 className="h-display" style={{ marginTop: 8, fontSize: 36 }}>Reports</h1>
        </div>
        <div className="row" style={{ gap: 4, background: "var(--paper-2)", padding: 4, borderRadius: 10, border: "1px solid var(--line)" }}>
          {[
            { id: "pending", label: `Pending (${pending.length})` },
            { id: "delivered", label: `Delivered (${delivered.length})` },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: "8px 16px", borderRadius: 7, fontSize: 13, fontWeight: 600,
              background: tab === t.id ? "var(--surface)" : "transparent",
              color: tab === t.id ? "var(--ink)" : "var(--muted)",
              boxShadow: tab === t.id ? "var(--shadow-1)" : "",
              transition: "all .18s",
            }}>{t.label}</button>
          ))}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "360px 1fr", gap: 16, alignItems: "start" }}>
        {/* LIST */}
        <div className="card" style={{ padding: 0, overflow: "hidden", maxHeight: "calc(100vh - 240px)", display: "flex", flexDirection: "column" }}>
          <div className="search" style={{ borderRadius: 0, border: 0, borderBottom: "1px solid var(--line)", padding: "12px 16px", minWidth: 0 }}>
            <Icons.Search size={15} stroke="var(--muted-2)" />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search patient…" />
          </div>
          <div className="scroll" style={{ overflowY: "auto", flex: 1 }}>
            {filtered.length === 0 && (
              <div style={{ padding: 32, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
                No patients in this list.
              </div>
            )}
            {filtered.map(p => (
              <button key={p.id} onClick={() => setSelected(p.id)} style={{
                width: "100%", display: "grid", gridTemplateColumns: "32px 1fr auto", gap: 12,
                padding: "14px 16px", textAlign: "left", alignItems: "center",
                borderBottom: "1px solid var(--line)",
                background: selected === p.id ? "var(--mint-soft)" : "transparent",
                borderLeft: selected === p.id ? "3px solid var(--mint)" : "3px solid transparent",
                paddingLeft: 13,
                transition: "background .18s",
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: "var(--paper-2)", display: "grid", placeItems: "center",
                  fontFamily: "var(--font-display)", fontSize: 14,
                }}>{p.name[0]}</div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)" }}>{p.dept} · <span className="mono">{p.id}</span></div>
                </div>
                <span className="pill" style={{
                  background: p.pdf ? "var(--mint-soft)" : "var(--paper-2)",
                  color: p.pdf ? "var(--mint-2)" : "var(--muted)", borderColor: "transparent",
                }}>
                  {p.pdf ? "Sent" : "Pending"}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* DETAIL */}
        {sel && (
          <div className="card" style={{ padding: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap" }}>
              <div style={{ minWidth: 0 }}>
                <div className="eyebrow">{sel.dept} · {sel.unit}</div>
                <h2 className="h-section" style={{ marginTop: 6, marginBottom: 0, lineHeight: 1.1, whiteSpace: "nowrap" }}>{sel.name}</h2>
                <div className="mono" style={{ fontSize: 12, color: "var(--muted)", marginTop: 8 }}>{sel.id} · {sel.captures} captures</div>
              </div>
              <div className="row" style={{ flex: "0 0 auto", gap: 8 }}>
                <button className="btn btn-ghost"><Icons.Eye size={14} /> View images</button>
                <button className="btn btn-ghost"><Icons.Mail size={14} /> Resend email</button>
              </div>
            </div>

            <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }} className="stagger">
              <Stat label="Captures" value={`${sel.captures}/5`} accent="var(--mint)" />
              <Stat label="AI flags" value={sel.flagged ? "2" : "0"} accent={sel.flagged ? "var(--coral)" : "var(--muted)"} />
              <Stat label="Status"   value={sel.pdf ? "Delivered" : "Awaiting"} accent={sel.pdf ? "var(--mint)" : "var(--gold)"} />
            </div>

            {/* Dropzone or delivered state */}
            {!sel.pdf ? (
              <div
                className={`dropzone ${dragOver ? "active" : ""}`}
                style={{ marginTop: 24 }}
                onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                onDragLeave={() => setDragOver(false)}
                onDrop={(e) => { e.preventDefault(); setDragOver(false); toast(`Report uploaded for ${sel.name}`); }}>
                <div style={{
                  width: 52, height: 52, borderRadius: 14,
                  background: "var(--mint-soft)", color: "var(--mint)",
                  display: "grid", placeItems: "center", margin: "0 auto 12px",
                }}><Icons.File size={22} /></div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>Drop report PDF here</div>
                <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 4 }}>or click to browse · PDF only · 10 MB max</div>
                <div className="row" style={{ justifyContent: "center", gap: 10, marginTop: 16 }}>
                  <button className="btn btn-mint" onClick={() => toast(`Report uploaded for ${sel.name}`)}>
                    <Icons.Upload size={14} /> Upload PDF
                  </button>
                </div>
              </div>
            ) : (
              <div style={{ marginTop: 24, padding: 20, background: "var(--mint-soft)", border: "1px solid var(--mint)", borderRadius: 14, display: "flex", alignItems: "center", gap: 16 }}>
                <div style={{ width: 48, height: 56, borderRadius: 6, background: "var(--surface)", border: "1px solid var(--line)", display: "grid", placeItems: "center" }}>
                  <Icons.File size={22} stroke="var(--mint-2)" />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{sel.id}_dental_report.pdf</div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>1.4 MB · Delivered to parent on {sel.date}</div>
                </div>
                <button className="btn btn-ghost"><Icons.Download size={14} /> Download</button>
              </div>
            )}

            <div style={{ marginTop: 22, padding: 16, background: "var(--paper-2)", border: "1px solid var(--line)", borderRadius: 12 }}>
              <div className="eyebrow">Auto-delivery</div>
              <div className="row" style={{ marginTop: 8, gap: 24, fontSize: 13 }}>
                <span className="row" style={{ gap: 6 }}><Icons.Mail size={14} stroke="var(--muted)" /> parent@aaravmehta.fam</span>
                <span className="row" style={{ gap: 6 }}><Icons.Phone size={14} stroke="var(--muted)" /> +91 ··· ··· 12345</span>
                <span className="row" style={{ gap: 6, marginLeft: "auto" }}><Icons.Clock size={14} stroke="var(--muted)" /> Sends within 5 min of upload</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Stat({ label, value, accent }) {
  return (
    <div style={{ padding: 14, borderRadius: 12, background: "var(--paper-2)", border: "1px solid var(--line)" }}>
      <div className="eyebrow">{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 28, marginTop: 4, color: accent }}>{value}</div>
    </div>
  );
}

window.ScreenReports = ScreenReports;

/* =========================================================
   RECORDS — searchable table + CSV export
   ========================================================= */

function ScreenRecords({ go }) {
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState("all");
  const [sort, setSort] = useState("id");

  const filtered = useMemo(() => {
    let arr = MOCK.patients.filter(p => {
      const s = search.toLowerCase();
      if (s && !(
        p.name.toLowerCase().includes(s) ||
        p.id.toLowerCase().includes(s) ||
        p.dept.toLowerCase().includes(s)
      )) return false;
      if (filter === "flagged" && !p.flagged) return false;
      if (filter === "delivered" && !p.pdf) return false;
      if (filter === "pending" && p.pdf) return false;
      return true;
    });
    arr.sort((a, b) => {
      if (sort === "id")   return a.id.localeCompare(b.id);
      if (sort === "name") return a.name.localeCompare(b.name);
      if (sort === "dept") return a.dept.localeCompare(b.dept);
      return 0;
    });
    return arr;
  }, [search, filter, sort]);

  return (
    <div className="screen col" style={{ gap: 20 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div className="eyebrow">{MOCK.org.cycle} · {MOCK.patients.length} records</div>
          <h1 className="h-display" style={{ marginTop: 8, fontSize: 36 }}>Records</h1>
        </div>
        <div className="row">
          <button className="btn btn-ghost"><Icons.Filter size={14} /> Filters</button>
          <button className="btn btn-primary" onClick={() => toast("Exporting CSV…")}>
            <Icons.Download size={14} /> Export CSV
          </button>
        </div>
      </div>

      {/* Filter chips */}
      <div className="row" style={{ flexWrap: "wrap", gap: 8 }}>
        <div className="search" style={{ minWidth: 360, flex: "0 0 auto" }}>
          <Icons.Search size={16} stroke="var(--muted-2)" />
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search by name, ID, section…" />
        </div>
        <div className="row" style={{ gap: 4, background: "var(--paper-2)", padding: 4, borderRadius: 10, border: "1px solid var(--line)" }}>
          {[
            { id: "all",        label: "All" },
            { id: "delivered",  label: "Delivered" },
            { id: "pending",    label: "Pending" },
            { id: "flagged",    label: "Flagged" },
          ].map(t => (
            <button key={t.id} onClick={() => setFilter(t.id)} style={{
              padding: "6px 14px", borderRadius: 7, fontSize: 12, fontWeight: 600,
              background: filter === t.id ? "var(--surface)" : "transparent",
              color: filter === t.id ? "var(--ink)" : "var(--muted)",
              boxShadow: filter === t.id ? "var(--shadow-1)" : "",
              transition: "all .18s",
            }}>{t.label}</button>
          ))}
        </div>
        <div className="row" style={{ marginLeft: "auto", color: "var(--muted)", fontSize: 12 }}>
          Showing <strong style={{ color: "var(--ink)", margin: "0 4px" }}>{filtered.length}</strong> of {MOCK.patients.length}
        </div>
      </div>

      {/* Table */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "100px 1.6fr 1fr 1fr 70px 110px 100px 90px",
          padding: "12px 20px",
          background: "var(--paper-2)",
          borderBottom: "1px solid var(--line)",
          fontSize: 10.5, letterSpacing: ".08em", textTransform: "uppercase",
          color: "var(--muted)", fontWeight: 600,
        }}>
          <div>ID</div>
          <div>Patient</div>
          <div>Section</div>
          <div>Organization</div>
          <div>Age</div>
          <div>Captures</div>
          <div>Report</div>
          <div>Date</div>
        </div>

        <div className="stagger">
        {filtered.map(p => (
          <div key={p.id} style={{
            display: "grid",
            gridTemplateColumns: "100px 1.6fr 1fr 1fr 70px 110px 100px 90px",
            padding: "13px 20px", alignItems: "center",
            borderBottom: "1px solid var(--line)",
            fontSize: 13.5, transition: "background .18s",
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--paper-2)"}
          onMouseLeave={(e) => e.currentTarget.style.background = ""}>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--muted)" }}>{p.id}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{
                width: 26, height: 26, borderRadius: 7,
                background: ["var(--mint-soft)","var(--coral-soft)","var(--gold-soft)","#ece8f7","#f7e3ec"][p.id.charCodeAt(p.id.length-1) % 5],
                color: "var(--ink)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--font-display)", fontSize: 13,
              }}>{p.name[0]}</div>
              <div>
                <div style={{ fontWeight: 600 }}>
                  {p.name}
                  {p.flagged && <span style={{ color: "var(--coral)", marginLeft: 6, fontSize: 11 }} title="Flagged">●</span>}
                </div>
              </div>
            </div>
            <div>
              <div>{p.dept}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--muted-2)" }}>{p.unit}</div>
            </div>
            <div style={{ fontSize: 13 }}>{MOCK.org.name.split(" ")[0]} Public</div>
            <div className="mono">{p.age}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span className="mono" style={{ fontSize: 12 }}>{p.captures}/5</span>
              <div style={{ flex: 1, height: 4, borderRadius: 99, background: "var(--paper-2)", overflow: "hidden" }}>
                <div style={{
                  width: `${(p.captures/5)*100}%`, height: "100%",
                  background: p.captures === 5 ? "var(--mint)" : "var(--coral)",
                  transition: "width 1s cubic-bezier(.2,.8,.2,1)"
                }} />
              </div>
            </div>
            <div>
              {p.pdf ? (
                <span className="pill mint"><span className="dot" />Sent</span>
              ) : (
                <span className="pill"><span className="dot" />Pending</span>
              )}
            </div>
            <div className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{p.date}</div>
          </div>
        ))}
        </div>

        <div className="row" style={{ padding: "12px 20px", background: "var(--paper-2)", borderTop: "1px solid var(--line)", fontSize: 12, color: "var(--muted)" }}>
          <span>Page 1 of 12</span>
          <span className="spacer" />
          <button className="btn btn-ghost" style={{ padding: "6px 10px" }}>Prev</button>
          <button className="btn btn-soft" style={{ padding: "6px 10px" }}>Next</button>
        </div>
      </div>

      {/* Legend */}
      <div className="row" style={{ gap: 24, fontSize: 12, color: "var(--muted)", justifyContent: "center" }}>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--mint)" }} /> Report delivered</span>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--coral)" }} /> Pending upload</span>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--coral)" }} /> Flagged case</span>
      </div>
    </div>
  );
}

window.ScreenRecords = ScreenRecords;

})();
