/* global React, Icon, MOUNJARO, WEGOVY, PATIENTS_SEED, ORDERS_SEED, fmtMoney, initials, calcAge, productById, formatDate */
const { useState: uSt, useMemo: uMm } = React;

// ===== Login =====
function Login({ onLogin }) {
  const [email, setEmail] = uSt("j.smith@beaumontaesthetics.co.uk");
  const [password, setPassword] = uSt("••••••••••");
  return (
    <div className="login-shell">
      <div className="login-left">
        <div className="login-brand">
          <div className="brand-mark" style={{ background: "var(--canvas)", color: "var(--ink)" }}>P</div>
          <div>
            <div style={{ fontWeight: 600 }}>Pharmacy365</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: "0.06em", textTransform: "uppercase" }}>For Clinics</div>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(255,255,255,0.5)", marginBottom: 16 }}>Prescriber portal</div>
          <h1 className="login-headline">A faster way to <em>prescribe,</em><br/>fulfil and follow up.</h1>
          <p style={{ marginTop: 24, maxWidth: 420, color: "rgba(255,255,255,0.7)", lineHeight: 1.55, fontSize: 14 }}>
            Direct supply of GLP-1 weight management treatments to your patients. Submit a prescription, pay once, we handle dispensing and tracked delivery from a GPhC-registered UK pharmacy.
          </p>
        </div>
        <div className="login-foot">
          <span>GPhC 9011432</span>
          <span>·</span>
          <span>MHRA registered</span>
          <span>·</span>
          <span>ISO 27001</span>
        </div>
      </div>

      <div className="login-right">
        <form className="login-card" onSubmit={(e) => { e.preventDefault(); onLogin(); }}>
          <div>
            <div className="login-eyebrow">Welcome back</div>
            <h2 className="login-title" style={{ marginTop: 6 }}>Sign in to your clinic</h2>
          </div>
          <div className="field">
            <label>Work email</label>
            <input className="input" value={email} onChange={(e) => setEmail(e.target.value)} type="email" />
          </div>
          <div className="field">
            <label style={{ display: "flex", justifyContent: "space-between" }}>
              <span>Password</span>
              <a href="#" style={{ color: "var(--accent)", textDecoration: "none", fontWeight: 400 }}>Forgot?</a>
            </label>
            <input className="input" value={password} onChange={(e) => setPassword(e.target.value)} type="password" />
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-3)" }}>
            <input type="checkbox" defaultChecked /> Keep me signed in on this device
          </label>
          <button type="submit" className="btn btn-accent btn-lg" style={{ justifyContent: "center" }}>
            <Icon.Lock /> Sign in securely
          </button>
          <div style={{ borderTop: "1px solid var(--line)", paddingTop: 16, fontSize: 12, color: "var(--ink-3)", textAlign: "center" }}>
            New clinic? <a href="#" style={{ color: "var(--accent)" }}>Request prescriber access →</a>
          </div>
        </form>
      </div>
    </div>
  );
}

// ===== Dashboard =====
function Dashboard({ orders, patients, setRoute }) {
  const stats = [
    { label: "This month", value: "£4,290", trend: "+18%", up: true, sub: "vs. last month" },
    { label: "Active patients", value: patients.filter(p => p.status === "active").length, trend: "+3", up: true, sub: "this week" },
    { label: "Orders fulfilled", value: 27, trend: "94%", up: true, sub: "on-time rate" },
    { label: "Awaiting review", value: orders.filter(o => o.status === "review").length, trend: "1 new", up: false, sub: "needs action" },
  ];
  const chartData = [12, 18, 15, 22, 28, 19, 26, 32, 24, 30, 38, 42];
  const months = ["May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr"];
  const max = Math.max(...chartData);

  const recentOrders = orders.slice(0, 5);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Tuesday, 28 April 2026</div>
          <h1 className="page-title">Good morning, Dr. Smith.</h1>
          <p className="page-sub">2 patients due for follow-up this week. 1 prescription is awaiting your review.</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost">Export</button>
          <button className="btn btn-accent" onClick={() => setRoute("new")}><Icon.New /> New prescription</button>
        </div>
      </div>

      <div className="stat-grid">
        {stats.map((s, i) => (
          <div key={i} className="stat">
            <div className="stat-label">{s.label}</div>
            <div className="stat-value tnum">{s.value}</div>
            <div className={"stat-trend" + (s.up ? "" : " down")}>
              {s.up ? <Icon.Up /> : <Icon.Down />} {s.trend} <span style={{ color: "var(--ink-4)", fontWeight: 400, marginLeft: 2 }}>· {s.sub}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="two-col">
        <div className="card">
          <div className="section-h">
            <div>
              <h2>Prescription volume</h2>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>Last 12 months · all GLP-1s</div>
            </div>
            <select className="select" style={{ width: "auto", padding: "6px 10px", fontSize: 12 }}>
              <option>All products</option>
              <option>Mounjaro only</option>
              <option>Wegovy only</option>
            </select>
          </div>
          <div className="chart">
            {chartData.map((v, i) => (
              <div key={i} className={"chart-bar" + (i === chartData.length - 1 ? " highlight" : "")} style={{ height: (v / max * 100) + "%" }} />
            ))}
          </div>
          <div className="chart-labels">{months.map((m, i) => <span key={i}>{m}</span>)}</div>
        </div>
        <div className="card">
          <div className="section-h">
            <h2>Recent activity</h2>
          </div>
          <div className="activity-row">
            <div className="activity-icon"><Icon.Pkg /></div>
            <div className="activity-body">
              <strong>PHC-2603-414</strong> shipped to D. O'Connor
              <div className="activity-time">2 hours ago · RM4421189GB</div>
            </div>
          </div>
          <div className="activity-row">
            <div className="activity-icon" style={{ background: "var(--gold-soft)", color: "var(--gold)" }}><Icon.Patients /></div>
            <div className="activity-body">
              New patient <strong>Ellen Markovic</strong> added
              <div className="activity-time">Yesterday · awaiting first prescription</div>
            </div>
          </div>
          <div className="activity-row">
            <div className="activity-icon" style={{ background: "var(--green-soft)", color: "var(--green)" }}><Icon.Card /></div>
            <div className="activity-body">
              Payment received for <strong>PHC-2603-409</strong>
              <div className="activity-time">Yesterday · £155.00</div>
            </div>
          </div>
          <div className="activity-row">
            <div className="activity-icon" style={{ background: "var(--rust-soft)", color: "var(--rust)" }}><Icon.Help /></div>
            <div className="activity-body">
              <strong>PHC-2603-381</strong> needs prescriber sign-off
              <div className="activity-time">2 days ago · J. Whitcombe</div>
            </div>
          </div>
        </div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: "20px 22px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 className="serif" style={{ fontSize: 22, margin: 0, fontWeight: 400, letterSpacing: "-0.02em" }}>Recent orders</h2>
          <button className="btn btn-link" onClick={() => setRoute("orders")}>View all <Icon.ChevronR /></button>
        </div>
        <table className="tbl">
          <thead><tr><th>Order</th><th>Patient</th><th>Product</th><th>Total</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {recentOrders.map(o => {
              const p = patients.find(p => p.id === o.patientId);
              const item = productById(o.items[0].pid);
              return (
                <tr key={o.id}>
                  <td className="tnum"><strong>{o.id}</strong><div className="muted" style={{ fontSize: 11 }}>{formatDate(o.date)}</div></td>
                  <td>
                    <div className="patient-cell">
                      <div className="patient-avatar">{initials(p.first, p.last)}</div>
                      <div><div className="patient-name">{p.first} {p.last}</div></div>
                    </div>
                  </td>
                  <td>{item.name} <span className="muted">· {item.strength}</span> {o.items[0].qty > 1 ? <span className="muted">× {o.items[0].qty}</span> : null}</td>
                  <td className="tnum"><strong>{fmtMoney(o.total)}</strong></td>
                  <td><StatusBadge status={o.status} /></td>
                  <td className="right"><Icon.ChevronR style={{ color: "var(--ink-4)" }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function StatusBadge({ status }) {
  const map = {
    active: ["badge-active", "Active"],
    paused: ["badge-pending", "Paused"],
    draft: ["badge-draft", "Draft"],
    review: ["badge-pending", "Review"],
    paid: ["badge-paid", "Paid"],
    shipped: ["badge-shipped", "Shipped"],
    cancelled: ["badge-cancelled", "Cancelled"],
  };
  const [cls, label] = map[status] || ["badge-draft", status];
  return <span className={"badge " + cls}><span className="badge-dot" />{label}</span>;
}

window.Login = Login;
window.Dashboard = Dashboard;
window.StatusBadge = StatusBadge;
