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

// ============================================================================
// REPORTING — dashboard + Ask Archy + aging
// ============================================================================
function Reporting() {
  const [report, setReport] = useState("overview");
  const [askOpen, setAskOpen] = useState(false);

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{
        padding: "10px 18px", borderBottom: "1px solid var(--border-hairline)",
        background: "var(--bg-surface)", display: "flex", alignItems: "center", gap: 10
      }}>
        <select className="select" style={{ width: 220 }} value={report} onChange={e => setReport(e.target.value)}>
          <optgroup label="Financial">
            <option value="overview">Financial Overview</option>
            <option value="production">Production by Provider</option>
            <option value="collections">Collections</option>
            <option value="aging">Patient Aging</option>
            <option value="adjustments">Adjustments</option>
          </optgroup>
          <optgroup label="Operational">
            <option value="schedule-util">Schedule Utilization</option>
            <option value="recall">Recall Performance</option>
            <option value="new-patients">New Patient Funnel</option>
          </optgroup>
        </select>
        <button className="btn sm"><I.Calendar size={12}/> Apr 1 – Apr 30, 2026</button>
        <button className="btn sm"><I.Filter size={12}/> Filters</button>
        <div className="spacer"/>
        <button className="btn sm" onClick={() => setAskOpen(true)}>
          <I.Sparkles size={12}/> Ask ToothPillow
        </button>
        <button className="btn sm"><I.Download size={12}/> Export</button>
      </div>

      {report === "overview" && <OverviewDashboard />}
      {report === "aging" && <AgingReport onAskAI={() => setAskOpen(true)} />}
      {report !== "overview" && report !== "aging" && <ReportPlaceholder name={report}/>}

      {askOpen && <AskArchy onClose={() => setAskOpen(false)} report={report}/>}
    </div>
  );
}

function OverviewDashboard() {
  return (
    <div style={{ flex: 1, overflow: "auto", padding: 20, background: "var(--bg-canvas)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 14 }}>
        <KPI label="Net production · today" value="$22,189" delta="+8.4%" sub="$14,820 completed · $7,369 scheduled" sparkline />
        <KPI label="Collections · MTD" value="$418,294" delta="+12.1%" sub="92% of production"/>
        <KPI label="A/R over 30 days" value="$54,182" delta="-3.2%" deltaDown sub="312 patients"/>
        <KPI label="New patients · MTD" value="48" delta="+15%" sub="5.72% of total visits"/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginBottom: 14 }}>
        <div className="card">
          <div className="card-head">
            <h3>Production by provider</h3>
            <span className="tiny muted">Today</span>
            <div className="spacer"/>
            <button className="btn icon ghost sm"><I.MoreHorizontal size={14}/></button>
          </div>
          <div style={{ padding: 18 }}>
            <ProductionBars/>
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            <h3>New vs existing</h3>
            <div className="spacer"/>
            <button className="btn icon ghost sm"><I.MoreHorizontal size={14}/></button>
          </div>
          <div style={{ padding: 18 }}>
            <DonutChart/>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-head"><h3>Goal pacing · April</h3><div className="spacer"/></div>
          <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12 }}>
            <Goal label="Practice production" current={418294} goal={500000} unit="$"/>
            <Goal label="Collections rate" current={92} goal={95} unit="%"/>
            <Goal label="New patients" current={48} goal={60} unit=""/>
            <Goal label="Hygiene re-app %" current={84} goal={90} unit="%"/>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>Recent activity</h3><div className="spacer"/></div>
          <div style={{ padding: "8px 0" }}>
            {[
              { who: "TDR", what: "completed appointment", subject: "Katie Filby", time: "2m ago", icon: I.Check, color: "var(--sage-600)" },
              { who: "JP", what: "submitted claim", subject: "$284 · Delta Dental", time: "11m ago", icon: I.FileText, color: "var(--blue-500)" },
              { who: "EL", what: "received payment", subject: "$420 · Joey Tribbiani", time: "24m ago", icon: I.DollarSign, color: "var(--sage-600)" },
              { who: "MR", what: "added treatment plan", subject: "Chase Rowley · $2,184", time: "1h ago", icon: I.Tooth, color: "var(--violet-500)" },
              { who: "SK", what: "uploaded EOB", subject: "MetLife · $1,840", time: "2h ago", icon: I.Upload, color: "var(--amber-700)" },
            ].map((a, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 14px" }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--bg-subtle)", display: "grid", placeItems: "center", color: a.color }}>
                  <a.icon size={14}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5 }}>
                    <span className="medium">{a.who}</span> {a.what} · <span className="muted">{a.subject}</span>
                  </div>
                </div>
                <div className="tiny muted">{a.time}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function KPI({ label, value, delta, deltaDown, sub, sparkline }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div className="tiny muted medium" style={{ marginBottom: 6 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: "-0.025em" }} className="tabular">{value}</div>
        {delta && (
          <span className="chip sm" style={{
            background: deltaDown ? "var(--sage-50)" : "var(--sage-50)",
            color: "var(--sage-700)",
            fontSize: 10.5
          }}>
            {deltaDown ? "↓" : "↑"} {delta}
          </span>
        )}
      </div>
      {sub && <div className="tiny muted" style={{ marginTop: 4 }}>{sub}</div>}
      {sparkline && (
        <svg width="100%" height="32" viewBox="0 0 200 32" style={{ marginTop: 8 }} preserveAspectRatio="none">
          <path d="M0 24 L20 22 L40 26 L60 18 L80 20 L100 14 L120 16 L140 10 L160 12 L180 6 L200 8 L200 32 L0 32 Z" fill="var(--sage-50)"/>
          <path d="M0 24 L20 22 L40 26 L60 18 L80 20 L100 14 L120 16 L140 10 L160 12 L180 6 L200 8" stroke="var(--sage-600)" strokeWidth="1.5" fill="none"/>
        </svg>
      )}
    </div>
  );
}

function ProductionBars() {
  const data = [
    { who: "Dr. Del Real", v: 6420, op: "Op 4" },
    { who: "Dr. Reilly", v: 5280, op: "Op 1" },
    { who: "Dr. Khoury", v: 4180, op: "Op 2" },
    { who: "Dr. Gupta", v: 3240, op: "Op 6" },
    { who: "Hyg. Park", v: 1690, op: "Op 3" },
    { who: "Hyg. Liang", v: 1379, op: "Op 5" },
  ];
  const max = Math.max(...data.map(d => d.v));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {data.map((d, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "140px 1fr 80px", gap: 12, alignItems: "center" }}>
          <div className="tiny" style={{ fontWeight: 500 }}>{d.who}</div>
          <div style={{ height: 8, background: "var(--bg-subtle)", borderRadius: 4, overflow: "hidden" }}>
            <div style={{
              width: `${(d.v / max) * 100}%`, height: "100%",
              background: `linear-gradient(90deg, var(--sage-400), var(--sage-600))`,
              borderRadius: 4
            }}/>
          </div>
          <div className="tiny tabular medium" style={{ textAlign: "right" }}>${d.v.toLocaleString()}</div>
        </div>
      ))}
    </div>
  );
}

function DonutChart() {
  const segments = [
    { label: "Existing patients", value: 94.28, color: "var(--sage-500)" },
    { label: "New patients", value: 5.72, color: "var(--mint-500)" },
  ];
  const r = 60, c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
      <svg width={160} height={160} viewBox="0 0 160 160">
        <circle cx="80" cy="80" r={r} fill="none" stroke="var(--bg-subtle)" strokeWidth="20"/>
        {segments.map((s, i) => {
          const len = (s.value / 100) * c;
          const el = (
            <circle key={i} cx="80" cy="80" r={r} fill="none" stroke={s.color} strokeWidth="20"
              strokeDasharray={`${len} ${c}`} strokeDashoffset={-offset}
              transform="rotate(-90 80 80)" strokeLinecap="round"/>
          );
          offset += len;
          return el;
        })}
        <text x="80" y="76" textAnchor="middle" fontSize="22" fontWeight="600" fill="var(--fg-primary)" className="tabular">5.72%</text>
        <text x="80" y="94" textAnchor="middle" fontSize="10" fill="var(--fg-tertiary)">new patients</text>
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, width: "100%" }}>
        {segments.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }}/>
            <span className="muted">{s.label}</span>
            <span className="spacer"/>
            <span className="tabular medium">{s.value}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Goal({ label, current, goal, unit }) {
  const pct = Math.min(100, (current / goal) * 100);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", marginBottom: 5 }}>
        <span className="tiny medium">{label}</span>
        <span className="spacer"/>
        <span className="tiny tabular muted">
          {unit === "$" ? "$" : ""}{current.toLocaleString()}{unit !== "$" ? unit : ""} / {unit === "$" ? "$" : ""}{goal.toLocaleString()}{unit !== "$" ? unit : ""}
        </span>
      </div>
      <div style={{ height: 6, background: "var(--bg-subtle)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{
          width: `${pct}%`, height: "100%",
          background: pct > 95 ? "var(--sage-500)" : pct > 75 ? "var(--mint-500)" : "var(--amber-500)",
          borderRadius: 3
        }}/>
      </div>
    </div>
  );
}

function AgingReport({ onAskAI }) {
  const rows = useMemo(() => {
    const carriers = ["MetLife PPO", "Delta Dental of California", "Aetna Open Access", "Cigna Dental Care", "Guardian", "United Concordia", "Self-pay", "Humana Dental", "Anthem BCBS"];
    return Array.from({ length: 18 }).map((_, i) => {
      const aging = [0, 30, 60, 90, 120][Math.floor(Math.random() * 5)];
      const tags = [
        ["Chandler Bing", 184.50], ["Joey Tribbiani", 250], ["Tom Haverford", 1200],
        ["Leslie Knope", 84], ["Ben Wyatt", 75], ["Rachel Green", 320], ["Phoebe Buffay", 60],
        ["Ross Geller", 145], ["Andy Dwyer", 420], ["April Ludgate", 84],
        ["Monica Geller", 2100], ["Chase Rowley", 421], ["Katie Filby", 184],
        ["Donna Meagle", 540], ["Jerry Gergich", 86], ["Ann Perkins", 218],
        ["Mark Brendanawicz", 412], ["Garry Gergich", 75],
      ][i];
      return {
        name: tags[0], amount: tags[1],
        carrier: carriers[i % carriers.length],
        last: ["3 days", "1 week", "2 weeks", "1 month", "2 months"][Math.floor(Math.random() * 5)],
        bucket: aging,
      };
    });
  }, []);

  return (
    <div style={{ flex: 1, overflow: "auto", padding: 20, background: "var(--bg-canvas)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10, marginBottom: 16 }}>
        {[
          ["Current", 218400, "var(--sage-500)"],
          ["1–30 days", 92140, "var(--mint-500)"],
          ["31–60 days", 38420, "var(--amber-500)"],
          ["61–90 days", 14820, "var(--amber-700)"],
          ["90+ days", 8240, "var(--rose-500)"],
        ].map(([label, v, c], i) => (
          <div key={i} className="card" style={{ padding: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: 2, background: c }}/>
              <span className="tiny muted medium">{label}</span>
            </div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }} className="tabular">${v.toLocaleString()}</div>
          </div>
        ))}
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Patient aging detail</h3>
          <span className="chip outline sm">2,416 rows</span>
          <div className="spacer"/>
          <button className="btn sm primary" onClick={onAskAI}>
            <I.Sparkles size={12}/> Filter with AI
          </button>
          <button className="btn sm"><I.Send size={12}/> Bulk payment request</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th style={{width: 28}}></th>
              <th>Patient</th>
              <th>Carrier</th>
              <th>Last activity</th>
              <th style={{ width: 100, textAlign: "right" }}>Amount</th>
              <th style={{ width: 120 }}>Bucket</th>
              <th style={{width: 40}}></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                <td><input type="checkbox" style={{accentColor:"var(--sage-600)"}}/></td>
                <td className="medium">{r.name}</td>
                <td className="tiny">{r.carrier}</td>
                <td className="tiny muted">{r.last}</td>
                <td className="tabular medium" style={{ textAlign: "right" }}>${r.amount.toFixed(2)}</td>
                <td>
                  <span className={"chip sm " + (r.bucket >= 90 ? "rose" : r.bucket >= 60 ? "amber" : r.bucket >= 30 ? "" : "sage")}>
                    {r.bucket === 0 ? "Current" : r.bucket + "+ days"}
                  </span>
                </td>
                <td><button className="btn icon ghost sm"><I.MoreHorizontal size={12}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ReportPlaceholder({ name }) {
  return (
    <div style={{ flex: 1, padding: 40, display: "grid", placeItems: "center" }}>
      <div className="placeholder" style={{ width: 480, height: 280 }}>
        {name.toUpperCase()} REPORT
      </div>
    </div>
  );
}

function AskArchy({ onClose, report }) {
  const [query, setQuery] = useState("");
  const [history, setHistory] = useState([
    { role: "user", text: "Hey ToothPillow, narrow this down by MetLife and greater than 30 days." },
    { role: "ai", text: "Filtered to 184 patients with MetLife coverage and balances older than 30 days. Total outstanding: $42,184. Would you like to send a bulk payment request?" },
  ]);

  const submit = () => {
    if (!query.trim()) return;
    setHistory([...history, { role: "user", text: query }, { role: "ai", text: "Working on that…" }]);
    setQuery("");
  };

  return (
    <div style={{
      position: "fixed", right: 0, top: 0, bottom: 0, width: 420,
      background: "var(--bg-surface)", borderLeft: "1px solid var(--border-hairline)",
      boxShadow: "var(--shadow-lg)", zIndex: 50,
      display: "flex", flexDirection: "column",
      animation: "side-in 220ms cubic-bezier(0.16, 1, 0.3, 1)"
    }}>
      <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border-hairline)", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: "linear-gradient(135deg, var(--sage-400), var(--violet-500))", display: "grid", placeItems: "center", color: "white" }}>
          <I.Sparkles size={14}/>
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Ask ToothPillow</div>
          <div className="tiny muted">Filtering: {report.replace(/-/g," ")}</div>
        </div>
        <div className="spacer"/>
        <button className="btn icon ghost" onClick={onClose}><I.X size={15}/></button>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
        {history.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.role === "user" ? "flex-end" : "flex-start",
            maxWidth: "85%",
            padding: "10px 14px",
            borderRadius: 12,
            background: m.role === "user" ? "var(--sage-50)" : "var(--bg-subtle)",
            color: m.role === "user" ? "var(--sage-700)" : "var(--fg-primary)",
            fontSize: 13, lineHeight: 1.5
          }}>{m.text}</div>
        ))}

        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 4 }}>
          <div className="tiny muted medium">Suggested</div>
          {[
            "Show me overdue patients with no payment plan",
            "Which providers are below goal?",
            "List new patients who haven't booked recall",
            "Top 10 patients by treatment plan value",
          ].map((s, i) => (
            <button key={i} className="btn sm" style={{ justifyContent: "flex-start", width: "100%", color: "var(--fg-secondary)" }}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div style={{ padding: 12, borderTop: "1px solid var(--border-hairline)" }}>
        <div style={{ display: "flex", gap: 6 }}>
          <input
            className="input"
            placeholder="Ask anything about this report…"
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={e => e.key === "Enter" && submit()}
          />
          <button className="btn primary icon" onClick={submit}><I.ArrowRight size={14}/></button>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// FORMS LIBRARY
// ============================================================================
function FormsLibrary() {
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("all");

  const cats = [
    { id: "all", label: "All forms", n: 216 },
    { id: "intake", label: "New patient intake", n: 24 },
    { id: "medical", label: "Medical history", n: 18 },
    { id: "consent", label: "Consents", n: 62 },
    { id: "financial", label: "Financial", n: 14 },
    { id: "ortho", label: "Ortho", n: 22 },
    { id: "surgical", label: "Surgical", n: 28 },
    { id: "cosmetic", label: "Cosmetic", n: 19 },
    { id: "perio", label: "Perio", n: 12 },
    { id: "custom", label: "Custom · practice", n: 17 },
  ];

  const forms = [
    { name: "Medical History (Standard)", cat: "medical", linked: 24, sent: 1840, used: "Daily" },
    { name: "New Patient Intake", cat: "intake", linked: 18, sent: 1240, used: "Daily" },
    { name: "Financial Policy", cat: "financial", linked: 12, sent: 920, used: "Daily" },
    { name: "HIPAA Notice", cat: "intake", linked: 4, sent: 1240, used: "Daily" },
    { name: "Botox / Filler Consent", cat: "consent", linked: 2, sent: 84, used: "Weekly" },
    { name: "Extraction Consent", cat: "surgical", linked: 6, sent: 320, used: "Weekly" },
    { name: "Implant Surgery Consent", cat: "surgical", linked: 4, sent: 124, used: "Weekly" },
    { name: "Root Canal Consent", cat: "consent", linked: 3, sent: 218, used: "Weekly" },
    { name: "Veneers Consent", cat: "cosmetic", linked: 2, sent: 42, used: "Monthly" },
    { name: "Nitrous Oxide Consent", cat: "consent", linked: 8, sent: 318, used: "Daily" },
    { name: "Periodontal Treatment", cat: "perio", linked: 6, sent: 184, used: "Weekly" },
    { name: "Pre-op Instructions: Surgery", cat: "surgical", linked: 6, sent: 124, used: "Weekly" },
    { name: "Ortho Treatment Consent", cat: "ortho", linked: 8, sent: 64, used: "Weekly" },
    { name: "Whitening Consent", cat: "cosmetic", linked: 1, sent: 32, used: "Monthly" },
    { name: "COVID-19 Screening", cat: "medical", linked: 18, sent: 1840, used: "Daily" },
  ];

  const filtered = forms.filter(f =>
    (category === "all" || f.cat === category) &&
    (search === "" || f.name.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div style={{ flex: 1, display: "flex", overflow: "hidden" }}>
      {/* Sidebar */}
      <div style={{ width: 220, borderRight: "1px solid var(--border-hairline)", background: "var(--bg-surface)", padding: "16px 8px", overflowY: "auto" }}>
        <div className="tiny muted medium" style={{ padding: "0 10px 8px", textTransform: "uppercase", letterSpacing: "0.06em" }}>Categories</div>
        {cats.map(c => (
          <div key={c.id} onClick={() => setCategory(c.id)} style={{
            display: "flex", alignItems: "center", gap: 8, padding: "7px 10px",
            borderRadius: "var(--r-sm)", cursor: "pointer",
            background: category === c.id ? "var(--sage-50)" : "transparent",
            color: category === c.id ? "var(--sage-700)" : "var(--fg-secondary)",
            fontSize: 12.5, fontWeight: category === c.id ? 600 : 450
          }}>
            <span>{c.label}</span>
            <span className="spacer"/>
            <span className="tiny muted tabular">{c.n}</span>
          </div>
        ))}
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--border-hairline)", display: "flex", alignItems: "center", gap: 10, background: "var(--bg-surface)" }}>
          <div className="search" style={{ minWidth: 320 }}>
            <I.Search size={14}/>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search 216 templates…"/>
          </div>
          <div className="spacer"/>
          <button className="btn sm"><I.Download size={12}/> Import</button>
          <button className="btn sm primary"><I.Plus size={12}/> New form</button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: 18, background: "var(--bg-canvas)" }}>
          <div className="card">
            <table className="table">
              <thead>
                <tr>
                  <th>Form name</th>
                  <th>Linked procedures</th>
                  <th>Auto-attach rules</th>
                  <th>Sent · 30d</th>
                  <th>Frequency</th>
                  <th style={{width: 80}}></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((f, i) => (
                  <tr key={i}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <I.FileText size={14} style={{ color: "var(--fg-tertiary)" }}/>
                        <span className="medium">{f.name}</span>
                      </div>
                    </td>
                    <td><span className="chip outline sm">{f.linked} procedures</span></td>
                    <td className="tiny muted">{f.cat === "intake" ? "On NP appt" : f.cat === "surgical" ? "On D71xx, D7140" : f.cat === "ortho" ? "On D8xxx" : "Linked rules"}</td>
                    <td className="tabular tiny">{f.sent.toLocaleString()}</td>
                    <td className="tiny">{f.used}</td>
                    <td>
                      <div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                        <button className="btn icon ghost sm"><I.Eye size={12}/></button>
                        <button className="btn icon ghost sm"><I.Edit size={12}/></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// SETTINGS — searchable
// ============================================================================
function Settings() {
  const [search, setSearch] = useState("");
  const [section, setSection] = useState("insurance-verif");

  const SETTINGS = [
    { id: "practice", label: "Practice info", group: "Account", icon: I.Building },
    { id: "users", label: "Users & roles", group: "Account", icon: I.Users },
    { id: "mfa", label: "Multi-factor authentication", group: "Account", icon: I.Lock },
    { id: "ip", label: "IP restrictions", group: "Account", icon: I.Shield },
    { id: "schedule-display", label: "Schedule display", group: "Schedule", icon: I.Calendar },
    { id: "emoji", label: "Emoji tags & flags", group: "Schedule", icon: I.Tag },
    { id: "operatories", label: "Operatories & providers", group: "Schedule", icon: I.MapPin },
    { id: "blocked", label: "Block-outs & holidays", group: "Schedule", icon: I.Clock },
    { id: "insurance-verif", label: "Insurance Verification", group: "Insurance", icon: I.Shield },
    { id: "carriers", label: "Carriers & fee schedules", group: "Insurance", icon: I.Receipt },
    { id: "claims-defaults", label: "Claims defaults", group: "Insurance", icon: I.FileText },
    { id: "form-reminders", label: "Form reminder cadence", group: "Communications", icon: I.Bell },
    { id: "recall", label: "Recall reminders", group: "Communications", icon: I.Refresh },
    { id: "templates", label: "Message templates", group: "Communications", icon: I.MessageSquare },
    { id: "payment", label: "Payment processing", group: "Billing", icon: I.CreditCard },
    { id: "fees", label: "Fee schedules", group: "Billing", icon: I.DollarSign },
    { id: "plans", label: "Payment plan defaults", group: "Billing", icon: I.Wallet },
    { id: "imaging-driver", label: "Imaging & sensors (Twain)", group: "Integrations", icon: I.XRay },
    { id: "pearl", label: "Pearl AI Imaging", group: "Integrations", icon: I.Sparkles },
    { id: "vyne", label: "Vyne (benefits auto-fill)", group: "Integrations", icon: I.Zap },
    { id: "exchange", label: "Dental Exchange (clearinghouse)", group: "Integrations", icon: I.GitBranch },
    { id: "erx-cfg", label: "ePrescribe (Surescripts)", group: "Integrations", icon: I.Pill },
  ];

  const filtered = SETTINGS.filter(s =>
    !search || s.label.toLowerCase().includes(search.toLowerCase()) ||
    s.group.toLowerCase().includes(search.toLowerCase())
  );

  const groups = Array.from(new Set(filtered.map(s => s.group)));
  const active = SETTINGS.find(s => s.id === section);

  return (
    <div style={{ flex: 1, display: "flex", overflow: "hidden" }}>
      <div style={{ width: 280, borderRight: "1px solid var(--border-hairline)", background: "var(--bg-surface)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: 12, borderBottom: "1px solid var(--border-hairline)" }}>
          <div className="search">
            <I.Search size={14}/>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search every setting…" autoFocus/>
          </div>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "8px 0" }}>
          {groups.map(g => (
            <div key={g}>
              <div className="tiny muted medium" style={{ padding: "10px 18px 4px", textTransform: "uppercase", letterSpacing: "0.06em" }}>{g}</div>
              {filtered.filter(s => s.group === g).map(s => (
                <div key={s.id} onClick={() => setSection(s.id)} style={{
                  display: "flex", alignItems: "center", gap: 10, padding: "7px 18px",
                  cursor: "pointer", fontSize: 13,
                  background: section === s.id ? "var(--sage-50)" : "transparent",
                  color: section === s.id ? "var(--sage-700)" : "var(--fg-primary)",
                  fontWeight: section === s.id ? 600 : 450,
                  borderLeft: section === s.id ? "2px solid var(--sage-500)" : "2px solid transparent"
                }}>
                  <s.icon size={14}/>
                  <span>{s.label}</span>
                  {search && <span className="chip sm sage" style={{marginLeft:"auto"}}>match</span>}
                </div>
              ))}
            </div>
          ))}
          {filtered.length === 0 && (
            <div className="muted tiny" style={{ padding: 20, textAlign: "center" }}>No settings match "{search}"</div>
          )}
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 28, background: "var(--bg-canvas)" }}>
        {section === "insurance-verif" && <InsuranceVerifSettings/>}
        {section === "emoji" && <EmojiSettings/>}
        {section === "form-reminders" && <FormReminderSettings/>}
        {section === "vyne" && <VyneSettings/>}
        {section !== "insurance-verif" && section !== "emoji" && section !== "form-reminders" && section !== "vyne" && (
          <div>
            <h2 style={{ margin: "0 0 6px", fontSize: 20, letterSpacing: "-0.02em" }}>{active?.label}</h2>
            <div className="muted small" style={{ marginBottom: 24 }}>Settings for this section.</div>
            <div className="placeholder" style={{ height: 320 }}>SETTINGS PANEL · {active?.label}</div>
          </div>
        )}
      </div>
    </div>
  );
}

function InsuranceVerifSettings() {
  const [auto, setAuto] = useState(true);
  const [days, setDays] = useState(5);
  const [sameMonth, setSameMonth] = useState(true);
  const [onInsChange, setOnInsChange] = useState(true);

  return (
    <div style={{ maxWidth: 720 }}>
      <h2 style={{ margin: "0 0 6px", fontSize: 20, letterSpacing: "-0.02em" }}>Insurance Verification</h2>
      <div className="muted small" style={{ marginBottom: 24 }}>
        Eligibility checks run automatically via Dental Exchange. Unlimited verifications are included on every plan.
      </div>

      <div className="card">
        <div className="card-head"><h3>Automated verification</h3></div>
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 16 }}>
          <Toggle
            label="Auto-verify eligibility before appointments"
            sub="Eligibility is checked automatically — no manual triggering needed."
            value={auto} onChange={setAuto}
          />
          <div style={{ display: "flex", alignItems: "center", gap: 12, paddingLeft: 0, opacity: auto ? 1 : 0.5 }}>
            <span className="small">Run</span>
            <select className="select" value={days} onChange={e => setDays(+e.target.value)} style={{ width: 100 }}>
              <option value={1}>1 day</option><option value={3}>3 days</option>
              <option value={5}>5 days</option><option value={7}>7 days</option><option value={14}>14 days</option>
            </select>
            <span className="small">before each appointment</span>
          </div>
          <div style={{ height: 1, background: "var(--border-hairline)" }}/>
          <Toggle
            label="Same-month verification only"
            sub="If a previous verification exists in the same calendar month, reuse it."
            value={sameMonth} onChange={setSameMonth}
          />
          <Toggle
            label="Re-verify when insurance changes"
            sub="Automatically re-run eligibility when a patient's insurance is added or modified."
            value={onInsChange} onChange={setOnInsChange}
          />
        </div>
      </div>

      <div className="card" style={{ marginTop: 18 }}>
        <div className="card-head"><h3>Last 24 hours</h3></div>
        <div style={{ padding: 16, display: "flex", gap: 20 }}>
          <Stat2 label="Auto-verified" value="184" delta="+12"/>
          <Stat2 label="Active coverage" value="178"/>
          <Stat2 label="Issues found" value="6" deltaTone="warn"/>
          <Stat2 label="Manual override" value="0"/>
        </div>
      </div>
    </div>
  );
}

function EmojiSettings() {
  const TAGS = [
    { e: "🇫🇷", label: "French speaking", on: true, user: true },
    { e: "🇪🇸", label: "Spanish speaking", on: true, user: true },
    { e: "🏍️", label: "Harley rider", on: true, user: true },
    { e: "💎", label: "VIP patient", on: false, user: true },
    { e: "👶", label: "Pediatric", on: true, user: false },
    { e: "🌿", label: "Recall overdue", on: true, user: false },
    { e: "💊", label: "Medication alert", on: true, user: false },
    { e: "🩺", label: "Medical condition", on: true, user: false },
    { e: "⚠️", label: "Allergy alert", on: true, user: false },
    { e: "💳", label: "Payment plan active", on: true, user: false },
    { e: "✅", label: "All forms complete", on: false, user: true },
    { e: "📝", label: "Submit Rx", on: false, user: true },
    { e: "🚫", label: "Text opt-out", on: true, user: false },
    { e: "🎖️", label: "Veteran", on: false, user: true },
    { e: "❤️", label: "Special care", on: true, user: false },
    { e: "🩸", label: "Bleeding disorder", on: true, user: false },
    { e: "✨", label: "Aesthetic interest", on: false, user: true },
    { e: "📞", label: "Unscheduled tx", on: true, user: false },
  ];
  const [tags, setTags] = useState(TAGS);
  const flip = (i) => setTags(tags.map((t, j) => j === i ? { ...t, on: !t.on } : t));

  return (
    <div style={{ maxWidth: 720 }}>
      <h2 style={{ margin: "0 0 6px", fontSize: 20, letterSpacing: "-0.02em" }}>Emoji tags & flags</h2>
      <div className="muted small" style={{ marginBottom: 24 }}>
        Tag toggles are per-user. Turning a tag off only affects your schedule view — other team members are not affected.
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Available tags</h3>
          <span className="chip outline sm">{tags.filter(t => t.on).length} active</span>
          <div className="spacer"/>
          <button className="btn sm"><I.Plus size={12}/> New tag</button>
        </div>
        <div style={{ padding: 8 }}>
          {tags.map((t, i) => (
            <div key={i} style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "8px 14px", borderRadius: "var(--r-sm)",
              cursor: "pointer"
            }}>
              <span style={{ fontSize: 18, width: 28, textAlign: "center" }}>{t.e}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{t.label}</div>
                <div className="tiny muted">{t.user ? "User-defined" : "System tag"}</div>
              </div>
              <Switch on={t.on} onClick={() => flip(i)}/>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function FormReminderSettings() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h2 style={{ margin: "0 0 6px", fontSize: 20, letterSpacing: "-0.02em" }}>Form reminder cadence</h2>
      <div className="muted small" style={{ marginBottom: 24 }}>
        Reminders for incomplete forms run automatically. Each message contains a personalised completion link.
      </div>

      <div className="card">
        <div className="card-head"><h3>Reminder schedule</h3></div>
        <div style={{ padding: 16 }}>
          <table className="table" style={{ background: "transparent" }}>
            <thead>
              <tr>
                <th>When</th>
                <th>Channel</th>
                <th>Template</th>
                <th style={{textAlign:"right"}}>Sent · 30d</th>
                <th style={{width: 60}}></th>
              </tr>
            </thead>
            <tbody>
              {[
                ["5 days before", "Email + SMS", "Standard reminder", 842],
                ["3 days before", "SMS", "Friendly nudge", 184],
                ["1 day before", "SMS", "Urgency reminder", 84],
                ["1 hour before", "SMS", "Last chance", 12],
              ].map((r, i) => (
                <tr key={i}>
                  <td className="medium">{r[0]}</td>
                  <td>{r[1]}</td>
                  <td className="tiny">{r[2]}</td>
                  <td className="tabular" style={{textAlign:"right"}}>{r[3]}</td>
                  <td><button className="btn icon ghost sm"><I.Edit size={12}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function VyneSettings() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h2 style={{ margin: "0 0 6px", fontSize: 20, letterSpacing: "-0.02em" }}>Vyne · Benefits auto-fill</h2>
      <div className="muted small" style={{ marginBottom: 24 }}>
        Vyne automatically populates insurance benefits and procedure history — approximately 70–80% of verification work.
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Connection</h3>
          <span className="chip sage sm"><span className="dot"/> Active</span>
        </div>
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 16 }}>
          <Toggle label="Auto-fill on new insurance entry" sub="Pulls benefits, copays, coverage %, deductibles, maximums." value={true}/>
          <Toggle label="Populate procedure history" sub="Last service dates auto-fill on patient lookup." value={true}/>
          <Toggle label="Mark auto-filled fields with ⚡" sub="Visual cue distinguishes auto-populated vs manually entered." value={true}/>
        </div>
      </div>
    </div>
  );
}

function Toggle({ label, sub, value, onChange }) {
  const [internal, setInternal] = useState(value);
  const v = onChange ? value : internal;
  const change = () => onChange ? onChange(!value) : setInternal(!internal);
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 14, cursor: "pointer" }} onClick={change}>
      <Switch on={v}/>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 500, fontSize: 13 }}>{label}</div>
        {sub && <div className="tiny muted" style={{ marginTop: 2 }}>{sub}</div>}
      </div>
    </div>
  );
}

function Switch({ on, onClick }) {
  return (
    <div onClick={onClick} style={{
      width: 32, height: 18, borderRadius: 9,
      background: on ? "var(--sage-500)" : "var(--bg-sunken)",
      position: "relative", flexShrink: 0, cursor: "pointer",
      transition: "background 140ms",
      border: on ? "1px solid var(--sage-600)" : "1px solid var(--border-hairline)"
    }}>
      <div style={{
        width: 14, height: 14, borderRadius: "50%",
        background: "white", position: "absolute",
        top: 1, left: on ? 16 : 1,
        transition: "left 140ms",
        boxShadow: "0 1px 2px oklch(0% 0 0 / 0.15)"
      }}/>
    </div>
  );
}

function Stat2({ label, value, delta, deltaTone }) {
  return (
    <div>
      <div className="tiny muted medium">{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
        <div style={{ fontSize: 20, fontWeight: 600 }} className="tabular">{value}</div>
        {delta && <span className={"chip sm " + (deltaTone === "warn" ? "amber" : "sage")}>{delta}</span>}
      </div>
    </div>
  );
}

// ============================================================================
// INSURANCE PAGE (carrier directory)
// ============================================================================
function InsurancePage() {
  return (
    <div style={{ flex: 1, overflow: "auto", padding: 24, background: "var(--bg-canvas)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 18 }}>
        <KPI label="Active carriers" value="42" sub="Last sync: 2 minutes ago"/>
        <KPI label="Verifications · today" value="184" delta="+12" sub="178 active · 6 issues"/>
        <KPI label="Claims awaiting payment" value="$84,184" sub="84 sent claims"/>
        <KPI label="Avg. days to pay" value="14.2" delta="-1.8d" sub="vs 16.0 last quarter"/>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Carriers</h3>
          <div className="spacer"/>
          <div className="search" style={{ minWidth: 240 }}>
            <I.Search size={13}/>
            <input placeholder="Search carrier…"/>
          </div>
          <button className="btn sm primary"><I.Plus size={12}/> Add carrier</button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Carrier</th>
              <th>Patients</th>
              <th>Active plans</th>
              <th>Fee schedule</th>
              <th>Avg. payment</th>
              <th>30d EOBs</th>
              <th>Auto-fill</th>
              <th style={{width:40}}></th>
            </tr>
          </thead>
          <tbody>
            {[
              ["Delta Dental of California", 482, 18, "Delta PPO 2026", "$184", 142, true],
              ["MetLife PPO", 318, 12, "MetLife 2026", "$162", 84, true],
              ["Aetna Open Access", 240, 8, "Aetna 2026", "$148", 62, true],
              ["Cigna Dental Care", 184, 6, "Cigna 2026", "$172", 48, true],
              ["Guardian", 142, 5, "Guardian 2026", "$155", 38, true],
              ["United Concordia", 120, 4, "UCCI 2026", "$140", 32, false],
              ["Anthem BCBS", 98, 4, "Anthem 2026", "$168", 28, true],
              ["Humana Dental", 84, 3, "Humana 2026", "$152", 24, true],
            ].map((r, i) => (
              <tr key={i}>
                <td className="medium">{r[0]}</td>
                <td className="tabular">{r[1]}</td>
                <td className="tabular">{r[2]}</td>
                <td className="tiny">{r[3]}</td>
                <td className="tabular medium">{r[4]}</td>
                <td className="tabular">{r[5]}</td>
                <td>
                  {r[6]
                    ? <span className="chip sage sm"><I.Zap size={10}/> Vyne</span>
                    : <span className="chip sm">Manual</span>}
                </td>
                <td><button className="btn icon ghost sm"><I.ChevronRight size={12}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { Reporting, FormsLibrary, Settings, InsurancePage });
