/* global React, ReactDOM, Sidebar, Topbar, Login, Dashboard, PatientList, BasketScreen, AllocateScreen, DeclareScreen, PayScreen, SignQueueScreen, PrescriptionsScreen, SignModal, OrderHistory, Settings, PATIENTS_SEED, ORDERS_SEED, PRESCRIPTIONS_SEED, productById, useTweaks, TweaksPanel, TweakSection, TweakColor */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#0E5D5E",
  "ink": "#0B1F2A",
  "canvas": "#F7F4EE",
  "rust": "#C2451F"
}/*EDITMODE-END*/;

function App() {
  const [authed, setAuthed] = useState(false);
  const [route, setRouteRaw] = useState("dashboard");
  const [routeData, setRouteData] = useState(null);
  const [patients, setPatients] = useState(PATIENTS_SEED);
  const [orders, setOrders] = useState(ORDERS_SEED);
  const [prescriptions, setPrescriptions] = useState(PRESCRIPTIONS_SEED);
  const [toast, setToast] = useState(null);

  // Multi-step wizard state
  const [basket, setBasket] = useState([]);
  const [allocations, setAllocations] = useState([]);
  const [declarations, setDeclarations] = useState({});

  // Sign modal
  const [signingRxId, setSigningRxId] = useState(null);

  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", tweaks.accent);
    root.style.setProperty("--ink", tweaks.ink);
    root.style.setProperty("--canvas", tweaks.canvas);
    root.style.setProperty("--rust", tweaks.rust);
    document.body.style.background = tweaks.canvas;
  }, [tweaks]);

  const setRoute = (r) => {
    if (typeof r === "string") {
      setRouteRaw(r);
      setRouteData(null);
      if (r === "basket") { setBasket([]); setAllocations([]); setDeclarations({}); }
    } else {
      setRouteRaw(r.name);
      setRouteData(r);
    }
    window.scrollTo(0, 0);
  };

  const addPatient = (p) => {
    const id = "p-" + String(patients.length + 1).padStart(3, "0");
    const np = { ...p, id, status: "active", orders: 0, lastOrder: "—" };
    setPatients(prev => [np, ...prev]);
    return np;
  };

  // Process payment: create one prescription per allocation
  const processPayment = () => {
    const baseNum = 1142 + prescriptions.length;
    const newRxs = allocations.map((a, i) => {
      const total = a.items.reduce((s, it) => s + productById(it.pid).price * it.qty, 0) + 4.95;
      return {
        id: "RX-26-" + (baseNum + i + 1),
        patientId: a.patientId,
        items: a.items,
        total,
        status: "unsigned",
        date: new Date().toISOString().slice(0, 10),
        directions: "Inject once weekly subcutaneously, on the same day each week.",
      };
    });
    setPrescriptions(prev => [...newRxs, ...prev]);
    setToast({ msg: `Payment confirmed · ${newRxs.length} prescription${newRxs.length > 1 ? "s" : ""} awaiting signature` });
    setTimeout(() => setToast(null), 3500);
    return newRxs.map(r => r.id);
  };

  const signPrescription = (rxId) => {
    const today = new Date().toISOString().slice(0, 10);
    setPrescriptions(prev => prev.map(rx => rx.id === rxId ? { ...rx, status: "signed", signedAt: today } : rx));
    setToast({ msg: `${rxId} signed · released to pharmacist` });
    setTimeout(() => setToast(null), 3500);
  };

  const unsignedCount = prescriptions.filter(rx => rx.status !== "signed").length;
  const signingRx = signingRxId ? prescriptions.find(rx => rx.id === signingRxId) : null;
  const signingPatient = signingRx ? patients.find(p => p.id === signingRx.patientId) : null;

  if (!authed) return <Login onLogin={() => setAuthed(true)} />;

  return (
    <div className="app">
      <Sidebar route={route} setRoute={setRoute} unsignedCount={unsignedCount} />
      <main className="main">
        <Topbar onNew={() => setRoute("basket")} unsignedCount={unsignedCount} onShowSign={() => setRoute("prescriptions")} />
        {route === "dashboard" && <Dashboard orders={orders} patients={patients} setRoute={setRoute} />}
        {route === "patients" && <PatientList patients={patients} setRoute={setRoute} openPatient={() => setRoute("basket")} onNewPatient={() => setRoute("basket")} />}
        {route === "orders" && <OrderHistory orders={orders} patients={patients} setRoute={setRoute} />}
        {route === "prescriptions" && <PrescriptionsScreen prescriptions={prescriptions} patients={patients} setRoute={setRoute} openSign={setSigningRxId} />}
        {route === "basket" && <BasketScreen basket={basket} setBasket={setBasket} setRoute={setRoute} />}
        {route === "allocate" && <AllocateScreen basket={basket} setBasket={setBasket} allocations={allocations} setAllocations={setAllocations} patients={patients} setRoute={setRoute} addPatient={addPatient} />}
        {route === "declare" && <DeclareScreen allocations={allocations} patients={patients} setRoute={setRoute} declarations={declarations} setDeclarations={setDeclarations} />}
        {route === "pay" && <PayScreen allocations={allocations} patients={patients} setRoute={setRoute} processPayment={processPayment} basket={basket} />}
        {route === "sign-queue" && <SignQueueScreen rxIds={routeData?.rxIds || []} prescriptions={prescriptions} patients={patients} setRoute={setRoute} openSign={setSigningRxId} />}
        {route === "settings" && <Settings />}
      </main>

      {signingRx && signingPatient && (
        <SignModal rx={signingRx} patient={signingPatient} onClose={() => setSigningRxId(null)} onSign={signPrescription} />
      )}

      {toast && (
        <div className="toast">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
          {toast.msg}
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Brand colours" subtitle="Re-skin without leaving the dashboard.">
          <TweakColor label="Accent (medical teal)" value={tweaks.accent} onChange={(v) => setTweak("accent", v)} />
          <TweakColor label="Ink (text & sidebar)" value={tweaks.ink} onChange={(v) => setTweak("ink", v)} />
          <TweakColor label="Canvas (background)" value={tweaks.canvas} onChange={(v) => setTweak("canvas", v)} />
          <TweakColor label="Alert (warnings)" value={tweaks.rust} onChange={(v) => setTweak("rust", v)} />
        </TweakSection>
        <TweakSection title="Presets">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => setTweak({ accent: "#0E5D5E", ink: "#0B1F2A", canvas: "#F7F4EE", rust: "#C2451F" })}>Clinical</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setTweak({ accent: "#1E5BBF", ink: "#0F1B2D", canvas: "#F4F6FB", rust: "#D4423B" })}>Trust blue</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setTweak({ accent: "#2F6B45", ink: "#1A2820", canvas: "#F6F4EC", rust: "#B5470F" })}>Botanical</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setTweak({ accent: "#7A4A2E", ink: "#1F1612", canvas: "#F8F2EA", rust: "#C2451F" })}>Apothecary</button>
          </div>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
