/* global React, I, PROVIDERS, STATUS_COLORS, APPT_TYPES, TODAY_PATIENTS, useState, useRef, useEffect, useMemo, Modal, Fragment */

// ============================================================================
// SCHEDULE
// ============================================================================

const HOURS = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
const ROW_H = 60; // px per hour
const COL_W = 168;

function timeToY(hhmm) {
  const [h, m] = hhmm.split(":").map(Number);
  return (h - HOURS[0]) * ROW_H + (m / 60) * ROW_H;
}
function fmtTime(hhmm) {
  const [h, m] = hhmm.split(":").map(Number);
  const ap = h >= 12 ? "p" : "a";
  const h12 = ((h + 11) % 12) + 1;
  return `${h12}:${String(m).padStart(2, "0")}${ap}`;
}

function ApptCard({ p, onClick, onHover, onHoverEnd, selected }) {
  const yTop = timeToY(p.time);
  const yEnd = timeToY(p.end);
  const h = yEnd - yTop;
  const prov = PROVIDERS.find(x => x.id === p.provider);
  const status = STATUS_COLORS[p.status];
  const type = APPT_TYPES[p.type];
  return (
    <div
      className="appt"
      onClick={onClick}
      onMouseEnter={onHover}
      onMouseLeave={onHoverEnd}
      style={{
        position: "absolute",
        top: yTop + 2,
        height: h - 4,
        left: 4,
        right: 4,
        background: type.color,
        borderRadius: 8,
        overflow: "hidden",
        cursor: "pointer",
        display: "flex",
        flexDirection: "column",
        boxShadow: selected
          ? `0 0 0 2px var(--sage-500), 0 4px 12px oklch(0% 0 0 / 0.08)`
          : `0 1px 2px oklch(0% 0 0 / 0.04)`,
        border: "1px solid oklch(0% 0 0 / 0.06)",
        transition: "box-shadow 140ms, transform 140ms",
      }}
    >
      {/* Top stripe = arrival status */}
      <div style={{ height: 4, background: status.color, flexShrink: 0 }} />
      {/* Body */}
      <div style={{ padding: "6px 8px 4px", flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 600, letterSpacing: "-0.01em" }}>
          <span className="tabular">{fmtTime(p.time)}</span>
          <span style={{ color: "var(--fg-tertiary)" }}>·</span>
          <span style={{ color: "var(--fg-secondary)", fontWeight: 500, fontSize: 11 }}>{prov.initials}</span>
          <div style={{ flex: 1 }} />
          {p.tags.slice(0, 2).map((t, i) => <span key={i} style={{ fontSize: 11 }}>{t}</span>)}
        </div>
        <div style={{ fontSize: 12.5, fontWeight: 550, marginTop: 2, letterSpacing: "-0.01em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {p.name}
        </div>
        {h > 50 && (
          <div style={{ fontSize: 11, color: "var(--fg-tertiary)", marginTop: "auto", overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>
            {p.typeLabel}
          </div>
        )}
        {h > 80 && p.alerts.length > 0 && (
          <div style={{ display: "flex", gap: 4, marginTop: 4, flexWrap: "wrap" }}>
            {p.alerts.slice(0, 2).map((a, i) => (
              <span key={i} className="chip rose sm" style={{ fontSize: 9.5, padding: "0 5px" }}>
                <I.AlertCircle size={9} /> {a}
              </span>
            ))}
          </div>
        )}
      </div>
      {/* Bottom stripe = provider */}
      <div style={{ height: 3, background: prov.color, flexShrink: 0 }} />
    </div>
  );
}

function HoverSnap({ patient, x, y }) {
  if (!patient) return null;
  const prov = PROVIDERS.find(p => p.id === patient.provider);
  const status = STATUS_COLORS[patient.status];
  return (
    <div className="pop" style={{ left: x, top: y, width: 320 }}>
      <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border-hairline)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div className={"avatar lg " + patient.avatar}>{patient.first[0]}{patient.last[0]}</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: "-0.01em" }}>{patient.name}</div>
            <div className="tiny muted">{patient.age} y/o · {patient.phone}</div>
          </div>
          <span className="chip sage sm"><span className="dot" />{status.label}</span>
        </div>
      </div>
      <div style={{ padding: "12px 14px", display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 12px", fontSize: 12 }}>
        <span className="muted">Time</span>
        <span className="tabular medium">{fmtTime(patient.time)} – {fmtTime(patient.end)} · Apr 30</span>
        <span className="muted">Provider</span>
        <span className="medium">{prov.name}</span>
        <span className="muted">Operatory</span>
        <span className="medium">{patient.op}</span>
        <span className="muted">Procedures</span>
        <span className="medium">{patient.typeLabel}</span>
        <span className="muted">Forms</span>
        <span>
          {patient.formsRed > 0 && <span className="chip rose sm">{patient.formsRed} outstanding</span>}
          {patient.formsRed > 0 && patient.formsGreen > 0 && " "}
          {patient.formsGreen > 0 && <span className="chip sage sm">{patient.formsGreen} complete</span>}
        </span>
        {patient.alerts.length > 0 && (
          <>
            <span className="muted">Alerts</span>
            <span style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              {patient.alerts.map((a, i) => <span key={i} className="chip rose sm"><I.AlertTriangle size={10} />{a}</span>)}
            </span>
          </>
        )}
      </div>
      <div style={{ padding: "10px 14px", borderTop: "1px solid var(--border-hairline)", background: "var(--bg-subtle)", display: "flex", gap: 6 }}>
        <button className="btn sm primary" style={{ flex: 1 }}>Open chart</button>
        <button className="btn sm icon"><I.MessageSquare size={13} /></button>
        <button className="btn sm icon"><I.Phone size={13} /></button>
      </div>
    </div>
  );
}

function Schedule({ selectedPatientId, onSelectPatient, view, setView }) {
  const [hover, setHover] = useState(null);
  const [draggingDate, setDraggingDate] = useState(false);

  const ops = ["Op 1", "Op 2", "Op 3", "Op 4", "Op 5", "Op 6"];
  const provByOp = (op) => PROVIDERS.find(p => p.op === op);

  // arrival summary
  const arrivals = useMemo(() => {
    const counts = { confirmed: 0, arrived: 0, seated: 0, inroom: 0, ready: 0, complete: 0, scheduled: 0 };
    TODAY_PATIENTS.forEach(p => { counts[p.status] = (counts[p.status] || 0) + 1; });
    return counts;
  }, []);

  return (
    <div className="content" style={{ flex: 1, minWidth: 0 }}>
      {/* Schedule body */}
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        {/* Day controls */}
        <div style={{
          padding: "12px 18px",
          borderBottom: "1px solid var(--border-hairline)",
          display: "flex",
          alignItems: "center",
          gap: 12,
          background: "var(--bg-surface)",
          flexShrink: 0,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
            <button className="btn icon"><I.ChevronLeft size={15} /></button>
            <button className="btn icon"><I.ChevronRight size={15} /></button>
            <button className="btn sm" style={{ marginLeft: 4 }}>Today</button>
          </div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>Thursday, April 30, 2026</div>
            <div className="tiny muted tabular">28 appointments · $22,189 booked · 4 operatories open</div>
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <ArrivalLegend counts={arrivals} />
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <SegToggle value={view} onChange={setView} options={[
              { v: "day", label: "Day", icon: I.Calendar },
              { v: "week", label: "Week", icon: I.Layers },
              { v: "huddle", label: "Huddle", icon: I.List },
            ]} />
            <button className="btn sm"><I.Filter size={13} /> Filter</button>
            <button className="btn sm primary"><I.Plus size={13} /> New appt</button>
          </div>
        </div>

        {/* Grid */}
        <div style={{ flex: 1, overflow: "auto", position: "relative" }}>
          <div style={{ display: "flex", minWidth: "fit-content", position: "relative" }}>
            {/* Time column */}
            <div style={{
              width: 56,
              position: "sticky",
              left: 0,
              background: "var(--bg-canvas)",
              borderRight: "1px solid var(--border-hairline)",
              zIndex: 5,
              flexShrink: 0,
            }}>
              <div style={{ height: 44, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }} />
              {HOURS.map(h => (
                <div key={h} style={{
                  height: ROW_H,
                  borderBottom: "1px solid var(--border-hairline)",
                  fontSize: 10.5,
                  color: "var(--fg-tertiary)",
                  padding: "3px 6px",
                  fontVariantNumeric: "tabular-nums",
                  textAlign: "right",
                }}>
                  {h === 12 ? "12p" : h > 12 ? `${h - 12}p` : `${h}a`}
                </div>
              ))}
            </div>

            {/* Operatory columns */}
            {ops.map(op => {
              const prov = provByOp(op);
              const ptsHere = TODAY_PATIENTS.filter(p => p.op === op);
              return (
                <div key={op} style={{ width: COL_W, flexShrink: 0, position: "relative" }}>
                  {/* Header */}
                  <div style={{
                    height: 44,
                    borderBottom: "1px solid var(--border-hairline)",
                    background: "var(--bg-surface)",
                    padding: "5px 10px",
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    position: "sticky", top: 0, zIndex: 4,
                    borderRight: "1px solid var(--border-hairline)",
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: prov.color }} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: "-0.01em" }}>{op}</div>
                      <div className="tiny muted" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {prov.initials} · {prov.name.replace(/^(Dr\.|Hyg\.) /, "")}
                      </div>
                    </div>
                  </div>
                  {/* Hour cells */}
                  <div style={{ position: "relative", height: HOURS.length * ROW_H, borderRight: "1px solid var(--border-hairline)" }}>
                    {HOURS.map((h, i) => (
                      <div key={h} style={{
                        position: "absolute", top: i * ROW_H, left: 0, right: 0, height: ROW_H,
                        borderBottom: "1px solid var(--border-hairline)",
                        background: i % 2 === 0 ? "transparent" : "oklch(98% 0.003 110)",
                      }}>
                        {/* 30min line */}
                        <div style={{ position: "absolute", top: ROW_H / 2, left: 8, right: 8, height: 1, borderTop: "1px dashed oklch(92% 0.005 110)" }} />
                      </div>
                    ))}
                    {/* Now line */}
                    <div style={{
                      position: "absolute",
                      top: timeToY("11:23"),
                      left: 0, right: 0,
                      borderTop: "2px solid var(--sage-500)",
                      zIndex: 3,
                      pointerEvents: "none",
                    }}>
                      <div style={{
                        position: "absolute", left: -3, top: -5,
                        width: 8, height: 8, borderRadius: "50%",
                        background: "var(--sage-500)",
                      }} />
                    </div>
                    {/* Appts */}
                    {ptsHere.map(p => (
                      <ApptCard
                        key={p.id}
                        p={p}
                        selected={p.id === selectedPatientId}
                        onClick={() => onSelectPatient(p.id)}
                        onHover={(e) => {
                          const r = e.currentTarget.getBoundingClientRect();
                          setHover({ id: p.id, x: r.right + 8, y: r.top });
                        }}
                        onHoverEnd={() => setHover(null)}
                      />
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Hover snap */}
      {hover && <HoverSnap patient={TODAY_PATIENTS.find(p => p.id === hover.id)} x={hover.x} y={hover.y} />}
    </div>
  );
}

function ArrivalLegend({ counts }) {
  const items = [
    ["Confirmed", "confirmed"],
    ["Arrived", "arrived"],
    ["Seated", "seated"],
    ["In room", "inroom"],
    ["Ready", "ready"],
    ["Complete", "complete"],
  ];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 11 }}>
      {items.map(([label, key]) => (
        <div key={key} style={{ display: "flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 2, background: STATUS_COLORS[key].color }} />
          <span style={{ color: "var(--fg-secondary)" }}>{label}</span>
          <span className="tabular" style={{ color: "var(--fg-tertiary)" }}>{counts[key] || 0}</span>
        </div>
      ))}
    </div>
  );
}

function SegToggle({ value, onChange, options }) {
  return (
    <div style={{
      display: "inline-flex",
      background: "var(--bg-subtle)",
      borderRadius: 8,
      padding: 2,
      gap: 1,
    }}>
      {options.map(o => {
        const IconC = o.icon;
        const active = value === o.v;
        return (
          <button key={o.v} onClick={() => onChange(o.v)} style={{
            padding: "5px 10px",
            borderRadius: 6,
            fontSize: 12,
            fontWeight: 500,
            display: "flex", alignItems: "center", gap: 5,
            background: active ? "var(--bg-surface)" : "transparent",
            color: active ? "var(--fg-primary)" : "var(--fg-tertiary)",
            boxShadow: active ? "var(--shadow-xs)" : "none",
          }}>
            {IconC && <IconC size={13} />}
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

// ============================================================================
// PATIENT SIDE PANEL
// ============================================================================
function PatientSidePanel({ patient, onClose, onOpenInsurance, onOpenChart, onOpenForm, onStartVisit }) {
  const [tab, setTab] = useState("overview");
  if (!patient) return null;
  const prov = PROVIDERS.find(p => p.id === patient.provider);

  return (
    <aside className="side-panel">
      {/* Header */}
      <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border-hairline)" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
          <div className={"avatar xl " + patient.avatar}>{patient.first[0]}{patient.last[0]}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>{patient.name}</div>
            <div className="tiny muted">
              {patient.age} y/o · DOB {fmtDate(patient.dob)}
            </div>
            <div style={{ display: "flex", gap: 4, marginTop: 6, flexWrap: "wrap" }}>
              {patient.alerts.length > 0 && patient.alerts.map((a, i) => (
                <span key={i} className="chip rose sm"><I.AlertTriangle size={10} /> {a}</span>
              ))}
              {patient.tags.map((t, i) => (
                <span key={i} className="chip outline sm">{t}</span>
              ))}
            </div>
          </div>
          <button className="btn icon ghost sm" onClick={onClose}><I.X size={14} /></button>
        </div>

        {/* Quick stats */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 8,
          marginTop: 12,
        }}>
          <StatTile label="Balance" value={`$${patient.balance.toFixed(2)}`} accent={patient.balance > 0 ? "rose" : "sage"} />
          <StatTile label="Family balance" value={`$${patient.familyBalance.toFixed(2)}`} accent={patient.familyBalance > 0 ? "amber" : "sage"} />
        </div>

        {/* Quick actions */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6, marginTop: 10 }}>
          <QuickAction icon={I.MessageSquare} label="Text" />
          <QuickAction icon={I.Phone} label="Call" />
          <QuickAction icon={I.Calendar} label="Schedule" />
        </div>
      </div>

      {/* Tabs */}
      <div style={{ padding: "0 12px", flexShrink: 0 }}>
        <div className="tabs">
          {[
            ["overview", "Overview"],
            ["forms", "Forms", patient.formsRed],
            ["clinical", "Clinical"],
            ["activity", "Activity"],
          ].map(([id, label, count]) => (
            <div key={id} className={"tab" + (tab === id ? " active" : "")} onClick={() => setTab(id)}>
              {label}
              {count > 0 && <span className="chip rose sm">{count}</span>}
            </div>
          ))}
        </div>
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflowY: "auto", padding: "12px 16px" }}>
        {tab === "overview" && (
          <div className="col" style={{ gap: 14 }}>
            <Section title="This appointment">
              <div className="col" style={{ gap: 6 }}>
                <KV label="Time"><span className="tabular medium">{fmtTime(patient.time)} – {fmtTime(patient.end)}</span></KV>
                <KV label="Provider">{prov.name}</KV>
                <KV label="Operatory">{patient.op}</KV>
                <KV label="Procedures">{patient.typeLabel}</KV>
                <KV label="Type"><span className="chip mint sm">{APPT_TYPES[patient.type].label}</span></KV>
              </div>
              <button className="btn primary sm" style={{ width: "100%", marginTop: 10, justifyContent: "center" }} onClick={onStartVisit}>
                <I.Mic size={13} /> Start visit with Pillow Scribe
              </button>
            </Section>

            <Section title="Financials">
              <table style={{ width: "100%", fontSize: 12 }}>
                <tbody>
                  <tr><td className="muted">UCR</td><td className="tabular" style={{ textAlign: "right" }}>$348.00</td></tr>
                  <tr><td className="muted">Negotiated rate</td><td className="tabular" style={{ textAlign: "right" }}>$241.00</td></tr>
                  <tr><td className="muted">Insurance estimate</td><td className="tabular" style={{ textAlign: "right", color: "var(--sage-700)" }}>−$192.80</td></tr>
                  <tr style={{ borderTop: "1px solid var(--border-hairline)" }}>
                    <td className="medium" style={{ paddingTop: 6 }}>Patient estimate</td>
                    <td className="tabular medium" style={{ textAlign: "right", paddingTop: 6 }}>$48.20</td>
                  </tr>
                </tbody>
              </table>
            </Section>

            <Section title="Insurance" right={<button className="btn ghost sm" onClick={onOpenInsurance}>View breakdown →</button>}>
              <div className="col" style={{ gap: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{patient.insurance}</div>
                    <div className="tiny muted">Primary · Subscriber: {patient.name}</div>
                  </div>
                  <span className="chip sage sm"><I.Check size={10} /> Verified</span>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  <MiniMetric label="Deductible" used="$50" total="$50" />
                  <MiniMetric label="Annual max" used="$485" total="$2,000" />
                </div>
              </div>
            </Section>

            <Section title="Family" right={<button className="btn ghost sm">View →</button>}>
              <div style={{ display: "flex", gap: 8 }}>
                <FamilyDot label="Self" name={patient.first} avatar={patient.avatar} />
                <FamilyDot label="Spouse" name="Mark" avatar="av-2" />
                <FamilyDot label="Child" name="Ava" avatar="av-3" />
                <FamilyDot label="Child" name="Leo" avatar="av-6" />
              </div>
            </Section>

            <Section title="Recent activity">
              <Timeline items={[
                { icon: I.Check, label: "Insurance verified via Vyne", time: "2h ago", color: "sage" },
                { icon: I.MessageSquare, label: "Confirmation SMS sent", time: "yesterday", color: "blue" },
                { icon: I.FileText, label: "Medical history updated via Kiosk", time: "2d ago", color: "violet" },
              ]} />
            </Section>
          </div>
        )}
        {tab === "forms" && (
          <div className="col" style={{ gap: 8 }}>
            <Section title="Required for this appointment">
              {[
                { name: "Medical History", status: patient.formsRed > 0 ? "pending" : "complete", note: patient.formsRed > 0 ? "Sent 2d ago · 1 reminder remaining" : "Submitted 5/12/26" },
                { name: "Financial Policy", status: "complete", note: "Signed 4/22/26" },
                { name: "HIPAA Privacy", status: "complete", note: "Signed 4/22/26" },
                { name: patient.type === "cosmetic" ? "Botox Consent" : "Photo Release", status: patient.formsRed > 1 ? "pending" : "complete", note: patient.formsRed > 1 ? "Not sent" : "Signed 5/01/26" },
              ].map((f, i) => (
                <FormRow key={i} f={f} onAction={onOpenForm} />
              ))}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 8 }}>
                <button className="btn sm"><I.PaperClip size={12} /> Attach</button>
                <button className="btn sm"><I.Smartphone size={12} /> Kiosk</button>
                <button className="btn sm"><I.Printer size={12} /> Print</button>
                <button className="btn sm primary"><I.Send size={12} /> Send fresh link</button>
              </div>
            </Section>
          </div>
        )}
        {tab === "clinical" && (
          <div className="col" style={{ gap: 14 }}>
            <Section title="Medical history">
              <div className="col" style={{ gap: 4 }}>
                <KV label="Conditions">
                  <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                    {(patient.alerts.includes("Diabetes") || patient.id === "p2") && <span className="chip rose sm">Diabetes</span>}
                    {patient.alerts.find(a => a.includes("Allergy")) && <span className="chip rose sm">{patient.alerts.find(a => a.includes("Allergy"))}</span>}
                    {patient.id === "p4" && <><span className="chip amber sm">Asthma</span><span className="chip amber sm">Anemia</span></>}
                    {!patient.alerts.length && patient.id !== "p4" && <span className="muted tiny">None reported</span>}
                  </div>
                </KV>
                <KV label="Medications">None</KV>
                <KV label="Last cleaning">Oct 14, 2025 · Hyg. Park</KV>
                <KV label="Last X-rays">FMX · Mar 3, 2024</KV>
              </div>
            </Section>
            <Section title="Outstanding treatment">
              <div className="col" style={{ gap: 6 }}>
                <TxRow code="D2391" desc="Composite – 1S, posterior" estimate="$48.20" />
                <TxRow code="D1110" desc="Adult prophylaxis" estimate="$0.00" />
                <TxRow code="D0274" desc="4 Bitewings" estimate="$0.00" />
              </div>
            </Section>
          </div>
        )}
        {tab === "activity" && (
          <Timeline items={[
            { icon: I.Mic, label: "Voice perio session · 8 sites flagged", time: "today, 9:14a", color: "violet" },
            { icon: I.Check, label: "Eligibility re-verified · Delta", time: "today, 6:00a", color: "sage" },
            { icon: I.MessageSquare, label: "Auto reminder: 24h", time: "yesterday, 9:00a", color: "blue" },
            { icon: I.FileText, label: "Treatment plan signed", time: "Apr 22", color: "sage" },
            { icon: I.CreditCard, label: "Payment $241.00 — Visa •• 4421", time: "Apr 22", color: "sage" },
            { icon: I.Calendar, label: "Appt scheduled", time: "Mar 18", color: "blue" },
          ]} />
        )}
      </div>

      {/* Footer */}
      <div style={{ padding: 12, borderTop: "1px solid var(--border-hairline)", display: "flex", gap: 6 }}>
        <button className="btn sm" style={{ flex: 1 }} onClick={onOpenChart}><I.Tooth size={13} /> Chart</button>
        <button className="btn sm" style={{ flex: 1 }}><I.FileText size={13} /> Notes</button>
        <button className="btn sm" style={{ flex: 1 }}><I.CreditCard size={13} /> Bill</button>
        <button className="btn sm icon"><I.MoreHorizontal size={13} /></button>
      </div>
    </aside>
  );
}

function Section({ title, right, children }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", marginBottom: 8 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: "var(--fg-tertiary)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{title}</div>
        <div style={{ flex: 1 }} />
        {right}
      </div>
      {children}
    </div>
  );
}
function KV({ label, children }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 8, fontSize: 12.5, lineHeight: 1.5 }}>
      <span className="muted">{label}</span>
      <span>{children}</span>
    </div>
  );
}
function StatTile({ label, value, accent }) {
  const accentColor = accent === "rose" ? "var(--rose-700)" : accent === "amber" ? "var(--amber-700)" : "var(--sage-700)";
  const bg = accent === "rose" ? "var(--rose-50)" : accent === "amber" ? "var(--amber-50)" : "var(--sage-50)";
  return (
    <div style={{ background: bg, borderRadius: 8, padding: "8px 10px" }}>
      <div className="tiny" style={{ color: accentColor, fontWeight: 500, opacity: 0.8 }}>{label}</div>
      <div className="tabular" style={{ fontSize: 15, fontWeight: 600, color: accentColor, letterSpacing: "-0.015em" }}>{value}</div>
    </div>
  );
}
function QuickAction({ icon: IconC, label }) {
  return (
    <button className="btn sm" style={{ flexDirection: "column", padding: "8px 6px", gap: 3 }}>
      <IconC size={14} />
      <span style={{ fontSize: 11, fontWeight: 500 }}>{label}</span>
    </button>
  );
}
function MiniMetric({ label, used, total }) {
  const pct = parseFloat(used.replace("$", "").replace(",", "")) / parseFloat(total.replace("$", "").replace(",", "")) * 100;
  return (
    <div style={{ background: "var(--bg-subtle)", borderRadius: 8, padding: 8 }}>
      <div className="tiny muted">{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 2 }}>
        <span className="tabular medium" style={{ fontSize: 13 }}>{used}</span>
        <span className="tiny muted">/ {total}</span>
      </div>
      <div style={{ height: 3, background: "var(--bg-sunken)", borderRadius: 2, marginTop: 4, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${Math.min(pct, 100)}%`, background: pct > 75 ? "var(--amber-500)" : "var(--sage-500)" }} />
      </div>
    </div>
  );
}
function FamilyDot({ label, name, avatar }) {
  return (
    <div style={{ textAlign: "center", flex: 1 }}>
      <div className={"avatar lg " + avatar} style={{ margin: "0 auto" }}>{name[0]}</div>
      <div className="tiny" style={{ marginTop: 4, fontWeight: 500 }}>{name}</div>
      <div className="tiny muted">{label}</div>
    </div>
  );
}
function Timeline({ items }) {
  return (
    <div className="col" style={{ gap: 0 }}>
      {items.map((it, i) => {
        const IconC = it.icon;
        return (
          <div key={i} style={{ display: "flex", gap: 10, padding: "6px 0", position: "relative" }}>
            <div style={{
              width: 24, height: 24, borderRadius: 6, flexShrink: 0,
              background: `var(--${it.color}-50)`, color: `var(--${it.color}-700)`,
              display: "grid", placeItems: "center",
            }}>
              <IconC size={13} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5 }}>{it.label}</div>
              <div className="tiny muted">{it.time}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}
function FormRow({ f, onAction }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 0", borderBottom: "1px solid var(--border-hairline)" }}>
      <span className={"form-pill " + f.status} style={{ minWidth: 92, justifyContent: "center" }}>
        {f.status === "complete" ? <I.Check size={11} /> : <I.AlertCircle size={11} />}
        {f.status === "complete" ? "Complete" : "Pending"}
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500 }}>{f.name}</div>
        <div className="tiny muted" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.note}</div>
      </div>
      <button className="btn icon sm ghost" onClick={() => onAction && onAction(f)}><I.MoreHorizontal size={12} /></button>
    </div>
  );
}
function TxRow({ code, desc, estimate }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 8px", borderRadius: 6, background: "var(--bg-subtle)" }}>
      <span className="mono" style={{ fontSize: 11, fontWeight: 600, color: "var(--sage-700)" }}>{code}</span>
      <span style={{ flex: 1, fontSize: 12.5 }}>{desc}</span>
      <span className="tabular medium" style={{ fontSize: 12.5 }}>{estimate}</span>
    </div>
  );
}

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

// ============================================================================
// INSURANCE POPOUT
// ============================================================================
function InsurancePopout({ open, onClose, patient }) {
  if (!open || !patient) return null;
  return (
    <Modal open={open} onClose={onClose} title="Insurance breakdown" width={780}>
      <div style={{ display: "flex", gap: 14, marginBottom: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600 }}>{patient.insurance}</div>
          <div className="tiny muted">Group #02184 · Policy #DD-{patient.id.toUpperCase()}448</div>
          <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
            <span className="chip sage sm"><I.Check size={10} /> Verified Apr 27</span>
            <span className="chip blue sm"><I.Refresh size={10} /> Auto re-check enabled</span>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8, width: 320 }}>
          <MetricBig label="Annual max" v="$2,000" sub="$485 used · $1,515 remaining" pct={24} />
          <MetricBig label="Deductible" v="$50" sub="$50 met · $0 remaining" pct={100} done />
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 12 }}>
        <div className="tab active">Coverage</div>
        <div className="tab">Limitations</div>
        <div className="tab">Procedure history <span className="count">126</span></div>
        <div className="tab">Notes</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <CoverageCol title="Diagnostic & Preventive" pct={100} rows={[
          ["Periodic exam D0120", "100%", "Every 6 mo"],
          ["Comprehensive exam D0150", "100%", "Once/3 yr"],
          ["Adult prophy D1110", "100%", "2/yr"],
          ["Bitewings D0274", "100%", "1/yr"],
          ["Fluoride D1206", "100%", "Under 19 only"],
        ]} />
        <CoverageCol title="Basic" pct={80} rows={[
          ["Composite (1S) D2391", "80%", "—"],
          ["Composite (2S) D2392", "80%", "—"],
          ["Amalgam D2140-2150", "80%", "—"],
          ["Root canal D3310", "80%", "Anterior"],
          ["Extraction D7140", "80%", "—"],
        ]} />
        <CoverageCol title="Major" pct={50} rows={[
          ["Crown porcelain D2740", "50%", "Once/5 yr per tooth"],
          ["Bridge pontic D6240", "50%", "—"],
          ["Implant D6010", "50%", "Lifetime max applies"],
          ["Denture full D5110", "50%", "Once/8 yr"],
        ]} />
        <CoverageCol title="Orthodontic" pct={50} rows={[
          ["Lifetime ortho max", "$1,500", "Child only"],
          ["Records D8660", "50%", "Once"],
          ["Comprehensive D8080", "50%", "Banded only"],
        ]} />
      </div>

      <div style={{ marginTop: 16, padding: 12, background: "var(--bg-subtle)", borderRadius: 8, display: "flex", alignItems: "center", gap: 10 }}>
        <I.Zap size={14} style={{ color: "var(--violet-500)" }} />
        <div style={{ flex: 1, fontSize: 12 }}>
          <span className="medium">Auto-populated via Vyne integration</span> — last refresh 3h ago. Fields marked
          {" "}<I.Zap size={10} style={{ color: "var(--violet-500)", display: "inline" }} />{" "}
          are pulled from the carrier portal automatically.
        </div>
        <button className="btn sm"><I.Refresh size={12} /> Re-check now</button>
      </div>
    </Modal>
  );
}

function MetricBig({ label, v, sub, pct, done }) {
  return (
    <div style={{ background: "var(--bg-subtle)", borderRadius: 8, padding: 10 }}>
      <div className="tiny muted">{label}</div>
      <div className="tabular" style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em" }}>{v}</div>
      <div className="tiny muted">{sub}</div>
      <div style={{ height: 4, background: "var(--bg-sunken)", borderRadius: 2, marginTop: 6, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${pct}%`, background: done ? "var(--sage-500)" : "var(--amber-500)" }} />
      </div>
    </div>
  );
}
function CoverageCol({ title, pct, rows }) {
  return (
    <div style={{ border: "1px solid var(--border-hairline)", borderRadius: 8, overflow: "hidden" }}>
      <div style={{ padding: "10px 12px", background: "var(--bg-subtle)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ fontSize: 12.5, fontWeight: 600 }}>{title}</div>
        <span className="chip sage sm">{pct}% covered</span>
      </div>
      <table style={{ width: "100%", fontSize: 12 }}>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} style={{ borderTop: "1px solid var(--border-hairline)" }}>
              <td style={{ padding: "7px 12px" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                  <I.Zap size={10} style={{ color: "var(--violet-500)" }} />
                  {r[0]}
                </span>
              </td>
              <td className="tabular medium" style={{ padding: "7px 8px", textAlign: "right" }}>{r[1]}</td>
              <td className="tiny muted" style={{ padding: "7px 12px 7px 4px", textAlign: "right" }}>{r[2]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, {
  Schedule, PatientSidePanel, InsurancePopout,
  fmtTime, fmtDate,
});
