/* global React, ReactDOM, ScreenStage, PhoneFrame, useState, useEffect, useRef,
   SplashScreen, LoginScreen, RegisterScreen, OtpScreen, ForgotScreen,
   HospitalScreen, HospitalRegScreen, DevicesScreen, PairingScreen,
   DeviceSetupScreen, CheckImageScreen, RoiScreen, RoiConfirmScreen,
   PatientRegScreen, PatientListScreen, MovePatientScreen, ConsentScreen,
   DeviceVitalsScreen, TrendsScreen, LiveVitalsScreen,
   AlertsScreen, ThresholdScreen, ProfileScreen, PersonalInfoScreen,
   ChangePasswordScreen, AffiliationsScreen,
   StaffMgmtScreen, StaffInviteScreen, StaffAccessScreen, I */

// ====================== Screen registry ======================
const SCREENS = [
  // Group: Onboarding
  { id: "splash",        name: "Splash",                grp: "Onboarding" },
  { id: "login",         name: "Sign in",               grp: "Onboarding" },
  { id: "register",      name: "Create account",        grp: "Onboarding" },
  { id: "otp",           name: "OTP verification",      grp: "Onboarding" },
  { id: "forgot",        name: "Forgot password",       grp: "Onboarding" },

  // Group: Hospitals
  { id: "hospital",      name: "Hospital list",         grp: "Hospitals" },
  { id: "hospital-reg",  name: "Register hospital",     grp: "Hospitals" },

  // Group: Devices
  { id: "devices",       name: "Device overview",       grp: "Devices",  tab: "devices" },
  { id: "pairing",       name: "Device pairing",        grp: "Devices" },
  { id: "device-setup",  name: "Setup · WiFi creds",    grp: "Setup" },
  { id: "check-image",   name: "Setup · Frame check",   grp: "Setup" },
  { id: "roi",           name: "Setup · Draw ROI",      grp: "Setup" },
  { id: "roi-confirm",   name: "Setup · Confirm ROI",   grp: "Setup" },

  // Group: Patients
  { id: "patient-reg",   name: "Register patient",      grp: "Patient" },
  { id: "patient-list",  name: "Patient list",          grp: "Patient" },
  { id: "move-patient",  name: "Move patient",          grp: "Patient" },
  { id: "consent",       name: "Consent & HIPAA",       grp: "Patient" },

  // Group: Monitoring
  { id: "device-vitals", name: "Vitals dashboard",      grp: "Monitoring", tab: "dashboard" },
  { id: "trends",        name: "Health trends",         grp: "Monitoring", tab: "trends" },
  { id: "live-vitals",   name: "Live vitals (ECG)",     grp: "Monitoring" },

  // Group: Alerts
  { id: "alerts",        name: "Alerts feed",           grp: "Alerts" },
  { id: "threshold",     name: "Alert thresholds",      grp: "Alerts" },

  // Group: Profile
  { id: "profile",       name: "Profile · Settings",    grp: "Profile",  tab: "profile" },
  { id: "personal",      name: "Personal info",         grp: "Profile" },
  { id: "password",      name: "Change password",       grp: "Profile" },
  { id: "affiliations",  name: "Hospital affiliations", grp: "Profile" },

  // Group: Staff
  { id: "staff-mgmt",    name: "Staff list",            grp: "Staff" },
  { id: "staff-invite",  name: "Invite staff",          grp: "Staff" },
  { id: "staff-access",  name: "Device access",         grp: "Staff" },
];

const GROUPS = ["Onboarding", "Hospitals", "Devices", "Setup", "Patient", "Monitoring", "Alerts", "Profile", "Staff"];

// Routing recommendations (forward transitions between common screens)
const FORWARD_FLOW = {
  splash: "login", login: "hospital", register: "otp", otp: "hospital",
  hospital: "devices", devices: "device-vitals",
  pairing: "device-setup", "device-setup": "check-image", "check-image": "roi", roi: "roi-confirm",
  "device-vitals": "live-vitals", trends: "live-vitals",
};

// ====================== App root ======================
function App() {
  const [current, setCurrent] = useState("splash");
  const [transition, setTransition] = useState("fade");
  const [roiStep, setRoiStep] = useState(0);
  const [tab, setTab] = useState("dashboard");
  const [hint, setHint] = useState(null);
  const [theme, setTheme] = useState("light");
  const lastHint = useRef(0);

  useEffect(() => {
    document.documentElement.dataset.theme = theme;
  }, [theme]);

  const go = (id, t) => {
    setTransition(t || "fwd");
    setCurrent(id);
    // surface route as hint at top of phone
    const meta = SCREENS.find(s => s.id === id);
    if (meta && meta.tab) setTab(meta.tab);
    if (meta) {
      const now = Date.now();
      if (now - lastHint.current > 50) {
        setHint({ name: meta.name, t: now });
        lastHint.current = now;
        setTimeout(() => setHint(h => (h && h.t === now ? null : h)), 1500);
      }
    }
  };

  const goTab = (newTab) => {
    setTab(newTab);
    const target = newTab === "dashboard" ? "device-vitals"
      : newTab === "trends" ? "trends"
      : newTab === "devices" ? "devices"
      : "profile";
    go(target, "fade");
  };

  // Keyboard shortcuts: arrow keys navigate flow
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "ArrowRight" || e.key === "ArrowDown") {
        const idx = SCREENS.findIndex(s => s.id === current);
        if (idx < SCREENS.length - 1) go(SCREENS[idx + 1].id, "fwd");
      }
      if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
        const idx = SCREENS.findIndex(s => s.id === current);
        if (idx > 0) go(SCREENS[idx - 1].id, "back");
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [current]);

  // Render current screen
  const renderScreen = (id) => {
    switch (id) {
      case "splash":        return <SplashScreen go={go} />;
      case "login":         return <LoginScreen go={go} />;
      case "register":      return <RegisterScreen go={go} />;
      case "otp":           return <OtpScreen go={go} />;
      case "forgot":        return <ForgotScreen go={go} />;
      case "hospital":      return <HospitalScreen go={go} />;
      case "hospital-reg":  return <HospitalRegScreen go={go} />;
      case "devices":       return <DevicesScreen go={go} tab={tab} onTab={goTab} />;
      case "pairing":       return <PairingScreen go={go} />;
      case "device-setup":  return <DeviceSetupScreen go={go} />;
      case "check-image":   return <CheckImageScreen go={go} />;
      case "roi":           return <RoiScreen go={go} step={roiStep} setStep={setRoiStep} />;
      case "roi-confirm":   return <RoiConfirmScreen go={go} step={roiStep} setStep={setRoiStep} />;
      case "patient-reg":   return <PatientRegScreen go={go} />;
      case "patient-list":  return <PatientListScreen go={go} />;
      case "move-patient":  return <MovePatientScreen go={go} />;
      case "consent":       return <ConsentScreen go={go} />;
      case "device-vitals": return <DeviceVitalsScreen go={go} tab={tab} onTab={goTab} />;
      case "trends":        return <TrendsScreen go={go} tab={tab} onTab={goTab} />;
      case "live-vitals":   return <LiveVitalsScreen go={go} />;
      case "alerts":        return <AlertsScreen go={go} />;
      case "threshold":     return <ThresholdScreen go={go} />;
      case "profile":       return <ProfileScreen go={go} tab={tab} onTab={goTab} />;
      case "personal":      return <PersonalInfoScreen go={go} />;
      case "password":      return <ChangePasswordScreen go={go} />;
      case "affiliations":  return <AffiliationsScreen go={go} />;
      case "staff-mgmt":    return <StaffMgmtScreen go={go} />;
      case "staff-invite":  return <StaffInviteScreen go={go} />;
      case "staff-access":  return <StaffAccessScreen go={go} />;
      default: return <div />;
    }
  };

  const meta = SCREENS.find(s => s.id === current);

  return (
    <div className="stage">
      {/* LEFT — Flow map */}
      <aside className="flowmap">
        <div className="logo">
          <div className="logo-mark">A<span>S</span></div>
          <div>
            <div className="logo-name">ArogyaSync</div>
            <div className="logo-sub">Clinical · Wireframe v1</div>
          </div>
        </div>

        <h1>App Flow</h1>
        <div className="sub">{SCREENS.length} screens · all paths</div>

        {GROUPS.map(g => (
          <div key={g}>
            <div className="grp">— {g}</div>
            {SCREENS.filter(s => s.grp === g).map((s, i) => {
              const idx = SCREENS.findIndex(x => x.id === s.id);
              return (
                <div key={s.id} className={"item " + (current === s.id ? "active" : "")}
                  onClick={() => go(s.id, current === s.id ? "fade" : "fwd")}>
                  <span className="num">{String(idx + 1).padStart(2, "0")}</span>
                  <span className="name">{s.name}</span>
                  <span className="arrow"><I.forward /></span>
                </div>
              );
            })}
          </div>
        ))}

        <div style={{ marginTop: 22, padding: 12, border: "1px dashed var(--line)", borderRadius: 10, background: "var(--paper-2)", fontSize: 11, color: "var(--ink-3)", lineHeight: 1.55 }}>
          <strong style={{ color: "var(--ink)" }}>Keyboard</strong>
          <div style={{ marginTop: 6 }}>
            <span className="kbd">←</span> <span className="kbd">→</span> step through screens<br />
            <span className="kbd">click</span> any item to jump
          </div>
        </div>
      </aside>

      {/* CENTER — Phone canvas */}
      <div className="phone-col">
        {/* theme toolbar */}
        <div className="toolbar">
          <div className="seg">
            <div className={"s " + (theme === "light" ? "on" : "")} onClick={() => setTheme("light")}>
              <I.sun /> Light
            </div>
            <div className={"s " + (theme === "dark" ? "on" : "")} onClick={() => setTheme("dark")}>
              <I.moon /> Dark
            </div>
          </div>
        </div>

        {/* hint */}
        {hint && (
          <div className="hint-bar" key={hint.t}>
            <span style={{ opacity: 0.6, textTransform: "uppercase", letterSpacing: 1, fontSize: 10 }}>Now showing</span>
            {hint.name}
          </div>
        )}

        <PhoneFrame>
          <ScreenStage current={renderScreen(current)} transitionType={transition} />
        </PhoneFrame>

        {/* canvas annotation labels */}
        <div style={{ position: "absolute", left: 30, bottom: 24, display: "flex", flexDirection: "column", gap: 4, fontSize: 11, color: "var(--ink-4)", letterSpacing: 0.6 }}>
          <span style={{ fontFamily: "JetBrains Mono", textTransform: "uppercase", fontSize: 10 }}>SCREEN {String(SCREENS.findIndex(s => s.id === current) + 1).padStart(2, "0")} / {SCREENS.length}</span>
          <span style={{ color: "var(--ink-2)", fontWeight: 700 }}>{meta && meta.name}</span>
        </div>
      </div>

      {/* RIGHT — Context panel */}
      <aside className="rightpanel">
        <div className="card">
          <div className="label">Current screen</div>
          <div className="name">{meta ? meta.name : "—"}</div>
          <div className="desc">{describeScreen(current)}</div>
        </div>

        <h2>Transitions in use</h2>
        <div className="card" style={{ padding: 12 }}>
          <TransitionLegend />
        </div>

        <h2>Motion language</h2>
        <div className="card" style={{ padding: 12 }}>
          <MotionLegend />
        </div>

        <h2>Wireframe palette</h2>
        <div className="card" style={{ padding: 12 }}>
          <Palette />
        </div>

        <h2>Flow shortcuts</h2>
        <div className="card flow-arrows">
          <div className="row">Splash <span className="arr">→</span> Login <span className="arr">→</span> Hospital</div>
          <div className="row">Devices <span className="arr">→</span> Pairing <span className="arr">→</span> Setup <span className="arr">→</span> ROI ×5</div>
          <div className="row">ROI <span className="arr">→</span> Patient Reg <span className="arr">→</span> Consent</div>
          <div className="row">Consent <span className="arr">→</span> Vitals Dashboard</div>
          <div className="row">Dashboard <span className="arr">→</span> Live Vitals <span className="arr">→</span> Alerts</div>
          <div className="row">Profile <span className="arr">→</span> Staff <span className="arr">→</span> Invite / Access</div>
        </div>
      </aside>
    </div>
  );
}

function TransitionLegend() {
  const items = [
    { l: "Shared-axis slide", k: "hierarchical (push)", t: "450ms · easeOutCubic", c: "var(--ink)" },
    { l: "Fade through", k: "tab switches", t: "300ms · standard", c: "var(--accent)" },
    { l: "Container transform", k: "card → detail", t: "500ms · emphasized", c: "var(--info)" },
    { l: "Bottom-sheet slide", k: "consent, sheets", t: "350ms · easeOutBack", c: "var(--warn)" },
    { l: "Circular reveal", k: "theme switch", t: "600ms", c: "#5a3da3" },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {items.map(i => (
        <div key={i.l} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12 }}>
          <div style={{ width: 8, height: 8, borderRadius: 999, background: i.c, marginTop: 6, flex: "0 0 auto" }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 800, color: "var(--ink)" }}>{i.l}</div>
            <div style={{ color: "var(--ink-3)" }}>{i.k} <span style={{ color: "var(--ink-4)" }}>· {i.t}</span></div>
          </div>
        </div>
      ))}
    </div>
  );
}

function MotionLegend() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="beat" style={{ display: "inline-grid", placeItems: "center", color: "var(--danger)" }}><I.heart /></span>
        <span><strong>Heartbeat pulse</strong> · HR icon · 1100ms loop</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="breath" style={{ width: 14, height: 14, borderRadius: 4, border: "1.5px solid #5a3da3", display: "inline-block" }} />
        <span><strong>Breath</strong> · RR card · 3.2s cycle</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="ripple-wrap" style={{ width: 16, height: 16, position: "relative", display: "inline-block" }}>
          <span className="ripple" style={{ borderColor: "var(--info)" }} />
          <span className="ripple r2" style={{ borderColor: "var(--info)" }} />
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--info)", display: "inline-block", margin: 4 }} />
        </span>
        <span><strong>Oxygen ripple</strong> · SpO₂ card · 2.4s</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="live-dot" />
        <span><strong>Live-data dot</strong> · pulse · 1.6s</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <svg width="22" height="12" viewBox="0 0 22 12"><path d="M0 6 L6 6 L8 2 L10 10 L12 0 L14 12 L16 6 L22 6" stroke="var(--danger)" strokeWidth="1.2" fill="none" /></svg>
        <span><strong>ECG scroll</strong> · waveform · 4.5s loop</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ display: "inline-block", width: 22, height: 12 }}>
          <svg width="22" height="12" viewBox="0 0 22 12"><path className="draw" d="M0 8 C4 5, 8 10, 14 4 S20 6, 22 6" stroke="var(--ink)" strokeWidth="1.4" fill="none" /></svg>
        </span>
        <span><strong>Spark/chart draw-in</strong> · 800–1200ms</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="shimmer" style={{ width: 22, height: 10, borderRadius: 3, display: "inline-block" }} />
        <span><strong>Skeleton shimmer</strong> · loading</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontFamily: "JetBrains Mono", fontWeight: 800, fontSize: 11 }}>72</span>
        <span><strong>Tabular number tick</strong> · vital updates</span>
      </div>
    </div>
  );
}

function Palette() {
  const items = [
    { c: "var(--ink)",     l: "Ink (primary text & buttons)" },
    { c: "var(--ink-3)",   l: "Mid grey (secondary text)" },
    { c: "var(--line)",    l: "Line (borders, dividers)" },
    { c: "var(--paper)",   l: "Paper (surfaces)" },
    { c: "var(--accent)",  l: "Accent · ArogyaSync green (action / live)" },
    { c: "var(--danger)",  l: "Critical (HR alerts, errors)" },
    { c: "var(--warn)",    l: "Warning (temp, thresholds)" },
    { c: "var(--info)",    l: "Info (SpO₂, devices, dialogs)" },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 12 }}>
      {items.map(i => (
        <div key={i.l} className="legend-row">
          <span className="legend-sq" style={{ background: i.c, borderColor: i.c === "var(--paper)" ? "var(--line)" : "transparent" }} />
          <span style={{ color: "var(--ink-2)" }}>{i.l}</span>
        </div>
      ))}
    </div>
  );
}

function describeScreen(id) {
  const d = {
    splash: "App boot. Logo + tagline + progress. Auto-routes to Login after 2.4s.",
    login: "Email or phone auth. Demo mode, Google SSO, link to register/forgot.",
    register: "Name, email, password + terms. Validates before enabling submit.",
    otp: "6-digit code with on-screen keypad. Auto-submits on completion. Resend timer.",
    forgot: "Email input → confirmation card. Returns to login.",
    hospital: "Multi-facility picker. Tap a card to enter that hospital's workspace.",
    "hospital-reg": "Form for new facility (name, location, pincode, type).",
    devices: "Stats carousel, search, online/offline filter, device cards with mini vitals.",
    pairing: "Secure setup scan. Tap a discovered unit to begin setup.",
    "device-setup": "Network details are handed to the unit through a secure setup flow.",
    "check-image": "Verifies the reading area is framed correctly. Live preview, retake/skip.",
    roi: "Draw 5 regions of interest (HR, SpO₂, RR, Temp, BP). Zoom/pan, color-coded.",
    "roi-confirm": "Per-vital confirmation with dimensions. Advances through 5 steps.",
    "patient-reg": "Demographics, bed, insurance, verbal-consent acknowledgement.",
    "patient-list": "Searchable patient roster with status, swipe actions to move/edit.",
    "move-patient": "Transfer monitoring from one device to another.",
    consent: "Per-purpose HIPAA toggles (vital monitoring, sharing, research) + bottom sheet.",
    "device-vitals": "Main dashboard. Status banner, 5 vital cards with sparklines, mini insights.",
    trends: "Multi-vital chart, time-range pills, summary stats. Tap → threshold settings.",
    "live-vitals": "Hero HR card with animated ECG, mini vital pills, windowed 3-vital chart.",
    alerts: "Severity-grouped feed (Now / Earlier). Critical pulses; ack/view actions.",
    threshold: "Per-vital warning + critical bands. Empty = disabled.",
    profile: "Profile card, theme toggle, account / admin / legal menu groups.",
    personal: "Name, contact, specialization, license — editable.",
    password: "Current + new + confirm with live strength meter.",
    affiliations: "Read-only list of hospitals the clinician has credentialed access to.",
    "staff-mgmt": "Staff roster (name, role, status). Add new via +. Long-press for access.",
    "staff-invite": "Email/phone invite with role + per-feature permission toggles.",
    "staff-access": "Per-staff device assignments. Toggle to grant/revoke.",
  };
  return d[id] || "";
}

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