// dashboard.jsx — Today's dashboard wired to the live store.

const { useState: useStateD, useMemo: useMemoD } = React;

function StatCard({ label, value, sub, accent }) {
  return (
    <div className="ms-stat">
      <div className="ms-stat-label">{label}</div>
      <div className="ms-stat-value" style={accent ? {color: accent} : null}>{value}</div>
      {sub && <div className="ms-stat-sub">{sub}</div>}
    </div>
  );
}

function statusFor(a) {
  switch (a.status) {
    case "in-room":  return { label: "In room",     cls: "warn" };
    case "checked-in": return { label: "Checked in", cls: "info" };
    case "confirmed":  return { label: "Confirmed",  cls: "success" };
    case "done":       return { label: "Done",       cls: "" };
    case "cancelled":  return { label: "Cancelled",  cls: "" };
    case "no-show":    return { label: "No-show",    cls: "" };
    default:           return { label: "Scheduled",  cls: "" };
  }
}

function ScheduleStrip({ appointments, onOpenEncounter, providerById }) {
  const t = window.MSStore.useT();
  if (!appointments.length) {
    return (
      <div className="card" style={{gridColumn: "span 2"}}>
        <div className="card-header">
          <div className="card-title">{t("dash.yourDay")}</div>
        </div>
        <div className="card-body" style={{padding: "32px 24px", textAlign: "center", color: "var(--ink-4)"}}>
          <Icon.Calendar size={28}/>
          <div style={{marginTop: 10, fontSize: 13.5}}>{t("dash.noToday")}</div>
        </div>
      </div>
    );
  }

  const counts = appointments.reduce((acc, a) => {
    if (a.status === "done") acc.done++;
    else if (a.status === "in-room") acc.inRoom++;
    return acc;
  }, { done: 0, inRoom: 0 });

  return (
    <div className="card" style={{gridColumn: "span 2"}}>
      <div className="card-header">
        <div>
          <div className="card-title">{t("dash.yourDay")}</div>
          <div style={{fontSize: 12.5, color: "var(--ink-3)", marginTop: 2}}>
            {t("sched.sub", { n: appointments.length })}
          </div>
        </div>
      </div>
      <div className="card-body" style={{paddingTop: 0}}>
        <div className="ms-timeline">
          {appointments.map((a, i) => {
            const isCurrent = a.status === "in-room";
            const status = statusFor(a);
            const provider = a.providerId ? providerById[a.providerId] : null;
            return (
              <div key={a.id} className={"ms-tl-row" + (isCurrent ? " is-current" : "")}>
                <div className="ms-tl-time">
                  <div className="ms-tl-time-main">{a.time || "—"}</div>
                  <div className="ms-tl-time-dur">{a.duration}m</div>
                </div>
                <div className="ms-tl-rail">
                  <div className="ms-tl-dot" style={isCurrent ? {background: "var(--accent-warn)"} : null}/>
                  {i < appointments.length - 1 && <div className="ms-tl-line"/>}
                </div>
                <button className="ms-tl-card" onClick={() => onOpenEncounter(a.id)}>
                  <div className="row" style={{gap: 12, alignItems: "flex-start"}}>
                    <div className="avatar">{(a.patientName || "?").split(" ").map(s => s[0]).slice(0, 2).join("").toUpperCase() || "?"}</div>
                    <div style={{flex: 1, minWidth: 0}}>
                      <div className="row" style={{gap: 8, marginBottom: 2}}>
                        <span style={{fontWeight: 600, fontSize: 14}}>{a.patientName || "Unknown patient"}</span>
                      </div>
                      <div className="row" style={{gap: 8, color: "var(--ink-3)", fontSize: 13}}>
                        <span>{a.type}</span>
                        {a.reason && a.reason !== a.type && <>
                          <span style={{color: "var(--ink-5)"}}>·</span>
                          <span style={{color: "var(--ink-3)"}}>{a.reason}</span>
                        </>}
                      </div>
                    </div>
                    <div className="col" style={{alignItems: "flex-end", gap: 6}}>
                      <span className={"badge" + (status.cls === "warn" ? " badge-warn" : status.cls === "success" ? " badge-success" : status.cls === "info" ? " badge-primary" : "")}>
                        <span className={"dot dot-" + (status.cls || "info")}/>
                        {status.label}
                      </span>
                      {provider && (
                        <div style={{fontSize: 12, color: "var(--ink-4)"}}>{provider.name}</div>
                      )}
                    </div>
                  </div>
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function TasksCard() {
  const t = window.MSStore.useT();
  const [items, setItems] = useStateD([]);
  const [done, setDone] = useStateD({});
  const [draft, setDraft] = useStateD("");
  function addTask(e) {
    if (e && e.preventDefault) e.preventDefault();
    const text = draft.trim();
    if (!text) return;
    const item = { id: "task-" + Date.now(), text, kind: "doc" };
    setItems(list => [item, ...list]);
    setDraft("");
  }
  return (
    <div className="card">
      <div className="card-header">
        <div className="card-title">{t("dash.tasks")}</div>
        <span className="badge">{items.filter(task => !done[task.id]).length} open</span>
      </div>
      <div className="card-body" style={{paddingTop: 0}}>
        <div className="row" style={{gap: 8, marginBottom: 12}}>
          <input className="input" value={draft} onChange={e => setDraft(e.target.value)} placeholder="Add a task…" />
          <button type="button" className="btn btn-primary btn-sm" disabled={!draft.trim()} onClick={addTask} style={{flexShrink: 0}}>
            <Icon.Plus size={14}/>Add
          </button>
        </div>
        <div className="col" style={{gap: 4}}>
          {items.length === 0 && (
            <div style={{padding: "16px 8px", color: "var(--ink-4)", fontSize: 13, textAlign: "center"}}>
              No tasks yet.
            </div>
          )}
          {items.map(t => {
            const isDone = !!done[t.id];
            const iconMap = { labs: Icon.Lab, rx: Icon.Pill, msg: Icon.Mail, doc: Icon.Document };
            const TI = iconMap[t.kind] || Icon.Document;
            return (
              <button key={t.id} className={"ms-task" + (isDone ? " is-done" : "")} onClick={() => setDone(d => ({...d, [t.id]: !d[t.id]}))}>
                <span className="ms-task-check">{isDone && <Icon.Check size={11}/>}</span>
                <span className="ms-task-icon"><TI size={15}/></span>
                <span className="ms-task-text">{t.text}</span>
                {t.urgent && !isDone && <span className="badge badge-danger" style={{flexShrink: 0}}>Urgent</span>}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function InboxCard({ onNav }) {
  const store = window.MSStore.useStore();
  const notifications = store.notifications || [];
  return (
    <div className="card">
      <div className="card-header">
        <div className="card-title">Notifications</div>
        <button className="btn btn-ghost btn-sm" onClick={() => onNav("notifications")}>View all <Icon.ChevronRight size={13}/></button>
      </div>
      <div className="card-body" style={{paddingTop: 0}}>
        <div className="col" style={{gap: 0}}>
          {notifications.length === 0 && <div style={{padding: 24, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>No notifications</div>}
          {notifications.slice(0, 5).map(m => (
            <button key={m.id} className="ms-inbox-row" onClick={() => store.markNotificationRead(m.id)} style={{textAlign: "left", width: "100%"}}>
              <div style={{flex: 1, minWidth: 0}}>
                <div className="row" style={{gap: 6, marginBottom: 2}}>
                  {!m.read_at && <span className="dot dot-info" style={{width: 6, height: 6}}/>}
                  <span style={{fontWeight: !m.read_at ? 600 : 500, fontSize: 13.5}}>{m.title}</span>
                  <span className="dim" style={{fontSize: 11.5, marginLeft: "auto"}}>{new Date(m.created_at).toLocaleDateString()}</span>
                </div>
                <div style={{fontSize: 12.5, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{m.body}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function Dashboard({ onNav, onOpenEncounter }) {
  const store = window.MSStore.useStore();
  const t = window.MSStore.useT();
  const profile = store.profile;
  const todayAppts = useMemoD(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today.getTime() + 86400000);
    return (store.appointments || []).filter(a => {
      const t = new Date(a.scheduledAt);
      return !isNaN(t) && t >= today && t < tomorrow;
    });
  }, [store.appointments]);

  const providerById = useMemoD(() => {
    const map = {};
    for (const p of (store.providers || [])) map[p.id] = p;
    return map;
  }, [store.providers]);

  const counts = useMemoD(() => {
    const c = { done: 0, inRoom: 0, remaining: 0 };
    const now = new Date();
    for (const a of todayAppts) {
      if (a.status === "done") c.done++;
      else if (a.status === "in-room") c.inRoom++;
      const t = new Date(a.scheduledAt);
      if (!isNaN(t) && t > now && a.status !== "done") c.remaining++;
    }
    return c;
  }, [todayAppts]);

  const lastName = profile && profile.name ? profile.name.replace(/^Dr\.?\s+/i, "").split(" ").pop() : null;
  const greetingPart = getGreetingPart();
  const greetingKey = greetingPart === "morning" ? "dash.greeting.morning" : greetingPart === "afternoon" ? "dash.greeting.afternoon" : "dash.greeting.evening";
  const lang = (window.MSi18n && window.MSi18n.getLang()) || "en";
  const greeting = lastName ? `${t(greetingKey)}, Dr. ${lastName}` : t(greetingKey);
  const today = new Date();
  const dayLabel = today.toLocaleDateString(lang === "es" ? "es-ES" : "en-US", { weekday: "long", month: "long", day: "numeric" });

  return (
    <div className="ms-page fade-in">
      <div className="ms-page-head">
        <div>
          <div className="eyebrow">{dayLabel}</div>
          <h1 className="h1" style={{marginTop: 4}}>{greeting}</h1>
          <div style={{color: "var(--ink-3)", marginTop: 6, fontSize: 14}}>
            {todayAppts.length === 0 ? t("dash.subNoVisits") : t("dash.subVisits", { n: counts.remaining })}
          </div>
        </div>
        <div className="row" style={{gap: 8}}>
          <button className="btn" onClick={() => onNav("schedule")}><Icon.CalendarPlus size={16}/>{t("dash.addAppointment")}</button>
          <button className="btn btn-primary" onClick={() => onNav("transcribe")}><Icon.Plus size={16}/>{t("dash.newVisit")}</button>
        </div>
      </div>

      <div className="ms-metrics">
        <StatCard label={t("dash.todaysVisits")} value={String(todayAppts.length)} sub={t("dash.todaysVisitsSub", { done: counts.done })}/>
        <StatCard label={t("dash.patientsOnFile")} value={String((store.patients || []).length)} sub={t("dash.patientsOnFileSub")}/>
        <StatCard label={t("dash.providers")} value={String((store.providers || []).length)} sub={t("dash.providersSub")}/>
        <StatCard label={t("dash.totalVisits")} value={String((store.analytics && store.analytics.sessions_this_month) || "—")} sub={t("dash.totalVisitsSub")}/>
      </div>

      <div className="ms-grid">
        <ScheduleStrip appointments={todayAppts} onOpenEncounter={onOpenEncounter} providerById={providerById}/>
        <div className="col" style={{gap: 16}}>
          <TasksCard/>
          <InboxCard onNav={onNav}/>
        </div>
      </div>
    </div>
  );
}

function getGreetingPart() {
  const h = new Date().getHours();
  if (h < 12) return "morning";
  if (h < 17) return "afternoon";
  return "evening";
}

window.Dashboard = Dashboard;
