/* global React, I, TODAY_PATIENTS, PROVIDERS, STATUS_COLORS, APPT_TYPES, useState, fmtTime, fmtDate */

// ============================================================================
// HUDDLE VIEW (list)
// ============================================================================
function Huddle({ onSelectPatient }) {
  const [selected, setSelected] = useState(new Set());
  const [filter, setFilter] = useState("all");

  const toggleAll = () => {
    if (selected.size === TODAY_PATIENTS.length) setSelected(new Set());
    else setSelected(new Set(TODAY_PATIENTS.map(p => p.id)));
  };
  const toggle = (id) => {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id); else next.add(id);
    setSelected(next);
  };

  const filtered = TODAY_PATIENTS.filter(p => {
    if (filter === "unconfirmed") return p.status === "scheduled";
    if (filter === "incomplete") return p.formsRed > 0;
    if (filter === "balance") return p.balance > 0;
    return true;
  }).sort((a, b) => a.time.localeCompare(b.time));

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {/* Controls */}
      <div style={{
        padding: "10px 18px",
        borderBottom: "1px solid var(--border-hairline)",
        background: "var(--bg-surface)",
        display: "flex",
        alignItems: "center",
        gap: 10,
      }}>
        <div className="row">
          <button className="btn icon"><I.ChevronLeft size={14} /></button>
          <button className="btn icon"><I.ChevronRight size={14} /></button>
          <div style={{ fontSize: 14, fontWeight: 600, marginLeft: 8 }}>Thursday, April 30, 2026</div>
          <span className="chip outline sm" style={{ marginLeft: 4 }}>28 patients</span>
        </div>
        <div className="spacer" />

        <FilterPills value={filter} onChange={setFilter} options={[
          { v: "all", label: "All", n: TODAY_PATIENTS.length },
          { v: "unconfirmed", label: "Unconfirmed", n: TODAY_PATIENTS.filter(p => p.status === "scheduled").length },
          { v: "incomplete", label: "Forms incomplete", n: TODAY_PATIENTS.filter(p => p.formsRed > 0).length },
          { v: "balance", label: "Has balance", n: TODAY_PATIENTS.filter(p => p.balance > 0).length },
        ]} />

        <div className="spacer" />

        {selected.size > 0 ? (
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <span className="chip sage sm">{selected.size} selected</span>
            <button className="btn sm"><I.Shield size={12} /> Verify eligibility</button>
            <button className="btn sm"><I.MessageSquare size={12} /> Bulk message</button>
            <button className="btn sm"><I.FileText size={12} /> Send forms</button>
          </div>
        ) : (
          <>
            <button className="btn sm"><I.Download size={12} /> Export</button>
            <button className="btn sm primary"><I.Shield size={12} /> Bulk verify eligibility</button>
          </>
        )}
      </div>

      {/* Table */}
      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="table" style={{ minWidth: 1100 }}>
          <thead>
            <tr>
              <th style={{ width: 36 }}>
                <CheckBox checked={selected.size === TODAY_PATIENTS.length} indeterminate={selected.size > 0 && selected.size < TODAY_PATIENTS.length} onChange={toggleAll} />
              </th>
              <th style={{ width: 70 }}>Time</th>
              <th style={{ width: 100 }}>Status</th>
              <th style={{ width: 60 }}>Room</th>
              <th>Patient</th>
              <th style={{ width: 120 }}>Provider</th>
              <th>Procedure</th>
              <th style={{ width: 90 }}>Tags</th>
              <th style={{ width: 100 }}>Balance</th>
              <th style={{ width: 140 }}>Eligibility</th>
              <th style={{ width: 90 }}>Forms</th>
              <th style={{ width: 40 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(p => {
              const prov = PROVIDERS.find(x => x.id === p.provider);
              const status = STATUS_COLORS[p.status];
              const elig = ["Active", "Active", "Active", "Active", "Pending", "Active", "Active", "Active", "Active", "Active", "Active", "Active", "Active"][parseInt(p.id.replace("p", "")) - 1] || "Active";
              return (
                <tr key={p.id} className={selected.has(p.id) ? "selected" : ""} onClick={() => onSelectPatient(p.id)} style={{ cursor: "pointer" }}>
                  <td onClick={e => { e.stopPropagation(); toggle(p.id); }}>
                    <CheckBox checked={selected.has(p.id)} onChange={() => toggle(p.id)} />
                  </td>
                  <td className="tabular medium">{fmtTime(p.time)}</td>
                  <td>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                      <span style={{ width: 7, height: 7, borderRadius: "50%", background: status.color }} />
                      <span style={{ fontSize: 12 }}>{status.label}</span>
                    </span>
                  </td>
                  <td className="medium">{p.op}</td>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div className={"avatar sm " + p.avatar}>{p.first[0]}{p.last[0]}</div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{p.name}</div>
                        <div className="tiny muted">{p.age} y/o</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                      <span style={{ width: 6, height: 6, borderRadius: "50%", background: prov.color }} />
                      <span style={{ fontSize: 12 }}>{prov.initials}</span>
                    </span>
                  </td>
                  <td style={{ fontSize: 12 }}>{p.typeLabel}</td>
                  <td>
                    {p.tags.length > 0 && (
                      <span style={{ fontSize: 13 }}>{p.tags.join(" ")}</span>
                    )}
                  </td>
                  <td className="tabular">
                    {p.balance > 0 ? (
                      <span className="medium" style={{ color: "var(--rose-700)" }}>${p.balance.toFixed(2)}</span>
                    ) : (
                      <span className="muted">$0.00</span>
                    )}
                  </td>
                  <td>
                    {elig === "Active" ? (
                      <span className="chip sage sm"><I.Check size={10} /> Active</span>
                    ) : (
                      <span className="chip amber sm"><I.Clock size={10} /> Processing…</span>
                    )}
                  </td>
                  <td>
                    {p.formsRed > 0 ? (
                      <span className="chip rose sm">{p.formsRed} pending</span>
                    ) : (
                      <span className="chip sage sm"><I.Check size={10} /> All</span>
                    )}
                  </td>
                  <td onClick={e => e.stopPropagation()}>
                    <button className="btn icon ghost sm"><I.MoreHorizontal size={12} /></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function FilterPills({ value, onChange, options }) {
  return (
    <div style={{ display: "inline-flex", gap: 4 }}>
      {options.map(o => (
        <button key={o.v} onClick={() => onChange(o.v)} className={"chip " + (value === o.v ? "sage" : "outline")} style={{
          padding: "4px 10px",
          fontSize: 12,
          fontWeight: value === o.v ? 600 : 500,
          cursor: "pointer",
        }}>
          {o.label}
          <span className="tabular" style={{ opacity: 0.6, marginLeft: 4 }}>{o.n}</span>
        </button>
      ))}
    </div>
  );
}

function CheckBox({ checked, indeterminate, onChange }) {
  const ref = React.useRef(null);
  React.useEffect(() => { if (ref.current) ref.current.indeterminate = !!indeterminate; }, [indeterminate]);
  return (
    <span style={{
      display: "inline-flex",
      width: 16, height: 16,
      borderRadius: 4,
      border: "1.5px solid " + (checked || indeterminate ? "var(--sage-500)" : "var(--border-strong)"),
      background: checked || indeterminate ? "var(--sage-500)" : "transparent",
      color: "white",
      alignItems: "center", justifyContent: "center",
      cursor: "pointer",
      transition: "all 120ms",
    }} onClick={onChange}>
      {checked && <I.Check size={11} sw={3} />}
      {indeterminate && !checked && <span style={{ width: 8, height: 2, background: "white", borderRadius: 1 }} />}
    </span>
  );
}

// ============================================================================
// ONLINE BOOKING
// ============================================================================
function OnlineBooking({ onSelectPatient }) {
  const requests = [
    { id: "b1", name: "Erin Chen", phone: "(512) 555-9011", email: "erin.chen@email.com", reqType: "New patient · Cleaning + exam", date: "May 5", time: "AM preferred", insurance: "Delta Dental", notes: "Have not been to dentist in 3+ years", submitted: "12 min ago", new: true },
    { id: "b2", name: "Marcus Hill", phone: "(512) 555-3320", email: "m.hill@email.com", reqType: "Existing · Tooth pain consult", date: "ASAP", time: "Any", insurance: "MetLife", notes: "Right side, pain when chewing for 4 days", submitted: "1h ago", new: true, urgent: true },
    { id: "b3", name: "Lily Park", phone: "(512) 555-4448", email: "lilypark@email.com", reqType: "Existing · Hygiene 6mo", date: "May 8 – May 12", time: "After 3pm", insurance: "Cigna", notes: "Prefer Hyg. Park if available", submitted: "3h ago", new: true },
    { id: "b4", name: "Dave Garcia", phone: "(512) 555-1101", email: "dave.g@email.com", reqType: "New patient · Consult", date: "Flexible", time: "Mornings", insurance: "Self-pay", notes: "Considering veneers, want to discuss options", submitted: "yesterday" },
  ];
  return (
    <div style={{ flex: 1, padding: 20, overflow: "auto" }}>
      <div style={{ maxWidth: 980, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.015em" }}>Online booking requests</div>
            <div className="tiny muted">From sunfielddental.com · No external platform to manage</div>
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn sm"><I.Globe size={12} /> Open booking page</button>
          <button className="btn sm" style={{ marginLeft: 6 }}><I.Settings size={12} /> Configure</button>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Inbox</h3>
            <span className="chip rose sm">{requests.filter(r => r.new).length} new</span>
            <div className="spacer" />
            <FilterPills value="new" onChange={() => {}} options={[
              { v: "new", label: "New", n: 3 },
              { v: "scheduled", label: "Scheduled", n: 12 },
              { v: "declined", label: "Declined", n: 2 },
            ]} />
          </div>
          <div className="card-body tight">
            {requests.map((r, i) => (
              <div key={r.id} style={{
                padding: "14px 16px",
                borderBottom: i < requests.length - 1 ? "1px solid var(--border-hairline)" : "none",
                display: "flex", gap: 14, alignItems: "flex-start",
                background: r.new ? "oklch(99% 0.005 110)" : "transparent",
              }}>
                <div className={"avatar lg av-" + ((i + 1) * 2 % 8 + 1)}>{r.name.split(" ").map(s => s[0]).join("")}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                    <span style={{ fontWeight: 600, fontSize: 14 }}>{r.name}</span>
                    {r.urgent && <span className="chip rose sm"><I.AlertTriangle size={10} /> Urgent</span>}
                    {r.new && <span className="chip sage sm">New</span>}
                    <span className="tiny muted">submitted {r.submitted}</span>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto 1fr", gap: "4px 16px", fontSize: 12, marginBottom: 6 }}>
                    <span className="muted">Type</span><span>{r.reqType}</span>
                    <span className="muted">Preferred</span><span>{r.date} · {r.time}</span>
                    <span className="muted">Phone</span><span className="tabular">{r.phone}</span>
                    <span className="muted">Insurance</span><span>{r.insurance}</span>
                  </div>
                  <div style={{ fontSize: 12, color: "var(--fg-secondary)", padding: "8px 10px", background: "var(--bg-subtle)", borderRadius: 6 }}>
                    "{r.notes}"
                  </div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "stretch", width: 130 }}>
                  <button className="btn sm primary">Schedule</button>
                  <button className="btn sm"><I.MessageSquare size={12} /> Reply</button>
                  <button className="btn sm ghost">Dismiss</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// ASAP LIST
// ============================================================================
function AsapList() {
  const list = [
    { name: "Hannah Sloane", phone: "(512) 555-0211", proc: "Adult Prophy", days: "Mon · Wed", time: "8a – 12p", since: "Apr 18", avatar: "av-3" },
    { name: "Bobby Newport", phone: "(512) 555-7766", proc: "MO Composite #19", days: "Any weekday", time: "After 2p", since: "Apr 14", avatar: "av-4" },
    { name: "Donna Meagle", phone: "(512) 555-8881", proc: "Crown #14", days: "Tue · Thu", time: "Any", since: "Apr 22", avatar: "av-7" },
    { name: "Jerry Gergich", phone: "(512) 555-3344", proc: "Comprehensive Exam + FMX", days: "Mon · Fri", time: "9a – 11a", since: "Apr 8", avatar: "av-2" },
    { name: "Mark Brendanawicz", phone: "(512) 555-9090", proc: "Implant Crown #30", days: "Any", time: "Mornings", since: "Apr 28", avatar: "av-5" },
  ];
  return (
    <div style={{ flex: 1, padding: 20, overflow: "auto" }}>
      <div style={{ maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.015em" }}>ASAP list · Fill cancellations smart</div>
            <div className="tiny muted">When a slot opens, the right patient is matched on procedure, day, and time window — no generic call-down list.</div>
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn sm"><I.Plus size={12} /> Add patient</button>
        </div>

        {/* Open slot panel */}
        <div style={{
          padding: 14,
          marginBottom: 14,
          background: "linear-gradient(180deg, var(--sage-50), var(--bg-surface))",
          border: "1px solid var(--sage-200)",
          borderRadius: 10,
          display: "flex", alignItems: "center", gap: 14,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 10, background: "var(--sage-500)", color: "white",
            display: "grid", placeItems: "center",
          }}><I.Sparkles size={18} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 14 }}>Opening today: Op 4 · 2:00p – 3:00p · Dr. Del Real</div>
            <div className="tiny muted">Andy Dwyer cancelled at 11:14a. 3 ASAP matches found.</div>
          </div>
          <span className="chip sage">3 matches</span>
          <button className="btn primary sm">View matches</button>
        </div>

        <div className="card">
          <table className="table">
            <thead>
              <tr>
                <th>Patient</th>
                <th>Wants</th>
                <th>Days</th>
                <th>Time window</th>
                <th>Waiting since</th>
                <th>Match score</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {list.map((r, i) => (
                <tr key={i}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div className={"avatar sm " + r.avatar}>{r.name.split(" ").map(s => s[0]).join("")}</div>
                      <div>
                        <div className="medium" style={{ fontSize: 13 }}>{r.name}</div>
                        <div className="tiny muted tabular">{r.phone}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ fontSize: 12.5 }}>{r.proc}</td>
                  <td style={{ fontSize: 12 }}>{r.days}</td>
                  <td style={{ fontSize: 12 }}>{r.time}</td>
                  <td style={{ fontSize: 12 }}><span className="tiny muted">{r.since}</span></td>
                  <td>
                    <MatchBar score={[92, 78, 64, 88, 41][i]} />
                  </td>
                  <td>
                    <div style={{ display: "flex", gap: 4 }}>
                      <button className="btn icon sm" title="Call"><I.Phone size={12} /></button>
                      <button className="btn icon sm" title="Text"><I.MessageSquare size={12} /></button>
                      <button className="btn sm primary">Offer slot</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
function MatchBar({ score }) {
  const color = score >= 80 ? "var(--sage-500)" : score >= 60 ? "var(--amber-500)" : "var(--rose-500)";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <div style={{ width: 60, height: 4, background: "var(--bg-sunken)", borderRadius: 2, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${score}%`, background: color }} />
      </div>
      <span className="tabular tiny medium">{score}%</span>
    </div>
  );
}

Object.assign(window, { Huddle, OnlineBooking, AsapList, FilterPills, CheckBox });
