/* global React */
(function () {
  const { useState, useEffect, useMemo, useRef, useCallback } = React;

  // ───────────────────────────────────────────────────────────────────────────
  // Hash router
  // ───────────────────────────────────────────────────────────────────────────
  function parseHash() {
    const h = (window.location.hash || "#/").replace(/^#/, "");
    const parts = h.split("/").filter(Boolean);
    // /                   -> home
    // /scales             -> list
    // /scale/:id          -> compile
    // /scale/:id/report   -> report preview
    return parts;
  }
  function navigate(path) {
    window.location.hash = path;
  }
  function useRoute() {
    const [route, setRoute] = useState(parseHash());
    useEffect(() => {
      const onChange = () => setRoute(parseHash());
      window.addEventListener("hashchange", onChange);
      return () => window.removeEventListener("hashchange", onChange);
    }, []);
    return route;
  }

  // ───────────────────────────────────────────────────────────────────────────
  // Persisted store (single record per scale, in localStorage)
  // ───────────────────────────────────────────────────────────────────────────
  function useScaleSession(scaleId) {
    const key = `rt:session:${scaleId}`;
    const [session, _setSession] = useState(() => {
      try {
        const raw = localStorage.getItem(key);
        if (raw) return JSON.parse(raw);
      } catch (e) {}
      return {
        patient: { firstName: "", lastName: "", dob: "" },
        clinician: "",
        notes: "",
        administeredAt: new Date().toISOString().slice(0, 16),
        answers: {},
        vasValue: null,
        numericValue: null,
        sliderValue: null,
        psfs: [{ name: "", score: null }, { name: "", score: null }, { name: "", score: null }]
      };
    });
    const setSession = (updater) => {
      _setSession((prev) => {
        const next = typeof updater === "function" ? updater(prev) : updater;
        try {localStorage.setItem(key, JSON.stringify(next));} catch (e) {}
        return next;
      });
    };
    return [session, setSession];
  }

  // ───────────────────────────────────────────────────────────────────────────
  // Top bar / footer
  // ───────────────────────────────────────────────────────────────────────────
  function TopBar({ active, now }) {
    return (
      <header className="rt-topbar">
      <div className="rt-topbar-inner">
        <a href="#/" className="rt-logo">
          <span className="rt-logo-mark">R</span>
          <span>Rehab Tools</span>
        </a>
        <nav className="rt-nav">
          <a href="#/" className={active === "home" ? "active" : ""}>Home</a>
          <a href="#/scales" className={active === "scales" ? "active" : ""}>Scale di valutazione</a>
          <a href="#/library" onClick={(e) => e.preventDefault()}>Documentazione</a>
        </nav>
        <div className="rt-topbar-meta">
          <span className="dot"></span>
          <span>U.O. Riabilitazione</span>
          <span>·</span>
          <span>{now}</span>
        </div>
      </div>
    </header>);
  }

  function Footer() {
    return (
      <footer className="rt-footer">
      <div className="rt-footer-inner">
        <div>© 2026 Rehab Tools · Strumento di supporto clinico ai professionisti sanitari. Non sostituisce in alcun modo il giudizio del professionista.</div>
        <div className="links">
          <a href="#" onClick={(e) => e.preventDefault()}>Privacy & GDPR</a>
          <a href="#" onClick={(e) => e.preventDefault()}>Riferimenti bibliografici</a>
          <a href="#" onClick={(e) => e.preventDefault()}>Contatti</a>
        </div>
      </div>
    </footer>);
  }

  // ───────────────────────────────────────────────────────────────────────────
  // Helpers
  // ───────────────────────────────────────────────────────────────────────────
  function formatDate(d) {
    if (!d) return "—";
    try {
      const dt = new Date(d);
      if (isNaN(dt)) return d;
      return dt.toLocaleDateString("it-IT", { day: "2-digit", month: "2-digit", year: "numeric" });
    } catch {return d;}
  }
  function formatDateTime(d) {
    if (!d) return "—";
    try {
      const dt = new Date(d);
      if (isNaN(dt)) return d;
      return dt.toLocaleString("it-IT", {
        day: "2-digit", month: "2-digit", year: "numeric",
        hour: "2-digit", minute: "2-digit"
      });
    } catch {return d;}
  }
  function ageFrom(dob) {
    if (!dob) return null;
    const d = new Date(dob);
    if (isNaN(d)) return null;
    const now = new Date();
    let a = now.getFullYear() - d.getFullYear();
    const m = now.getMonth() - d.getMonth();
    if (m < 0 || m === 0 && now.getDate() < d.getDate()) a--;
    return a;
  }
  function interpret(scale, score) {
    if (score == null || isNaN(score)) return null;
    return scale.interpretation.find((i) => score >= i.from && score <= i.to) || null;
  }

  // ───────────────────────────────────────────────────────────────────────────
  // Score computation (shared by compile + report)
  // ───────────────────────────────────────────────────────────────────────────
  const ITEMS_KEY_MAP = {
    WOMAC: "RT_WOMAC_ITEMS", LEFS: "RT_LEFS_ITEMS", BERG: "RT_BERG_ITEMS",
    FGA: "RT_FGA_ITEMS", SCIM: "RT_SCIM_ITEMS", SARA: "RT_SARA_ITEMS",
    CPAX: "RT_CPAX_ITEMS", PFIT: "RT_PFIT_ITEMS", MRCSS: "RT_MRCSS_ITEMS",
    QUICKDASH: "RT_QUICKDASH_ITEMS"
  };

  function computeScore(scale, session) {
    const form = scale.form;
    let score = null, total = 0, completion = 0, unit = null;

    if (form === "barthel") {
      const items = window.RT_BARTHEL_ITEMS || [];
      total = 100;
      const ans = items.filter(it => session.answers[it.id] != null);
      completion = items.length ? ans.length / items.length : 0;
      if (ans.length > 0) score = ans.reduce((s, it) => s + session.answers[it.id], 0);

    } else if (form === "vas") {
      total = 10;
      completion = session.vasValue != null ? 1 : 0;
      score = session.vasValue;

    } else if (form === "radioItems" || form === "mrc") {
      const items = form === "mrc"
        ? (window.RT_MRC_ITEMS || [])
        : (window[ITEMS_KEY_MAP[scale.itemsKey]] || []);
      if (items.length) {
        total = items.reduce((s, it) => s + Math.max(...it.options.map(o => o.value)), 0);
        const ans = items.filter(it => session.answers[it.id] != null);
        completion = ans.length / items.length;
        if (ans.length > 0) score = ans.reduce((s, it) => s + session.answers[it.id], 0);
      }

    } else if (form === "quickdash") {
      const items = window.RT_QUICKDASH_ITEMS || [];
      total = 100;
      const ans = items.filter(it => session.answers[it.id] != null);
      completion = items.length ? ans.length / items.length : 0;
      if (ans.length === items.length && items.length > 0) {
        const sum = ans.reduce((s, it) => s + session.answers[it.id], 0);
        score = Math.round(((sum - items.length) / (items.length * 4)) * 100);
      }

    } else if (form === "tinetti") {
      const allItems = [
        ...(window.RT_TINETTI_BALANCE_ITEMS || []),
        ...(window.RT_TINETTI_GAIT_ITEMS || [])
      ];
      total = 28;
      const ans = allItems.filter(it => session.answers[it.id] != null);
      completion = allItems.length ? ans.length / allItems.length : 0;
      if (ans.length > 0) score = ans.reduce((s, it) => s + session.answers[it.id], 0);

    } else if (form === "ordinal") {
      total = Math.max(...(scale.singleOptions || [{ value: 0 }]).map(o => o.value));
      const v = session.answers.__ordinal;
      completion = v != null ? 1 : 0;
      score = v != null ? v : null;

    } else if (form === "numeric") {
      unit = scale.unitShort || scale.unit || "";
      const v = session.numericValue;
      const valid = v != null && v !== "" && !isNaN(Number(v)) && Number(v) >= 0;
      completion = valid ? 1 : 0;
      score = valid ? Number(v) : null;
      total = scale.reportMax || 100;

    } else if (form === "slider") {
      total = 10;
      const v = session.sliderValue;
      completion = v != null ? 1 : 0;
      score = v != null ? v : null;

    } else if (form === "eq5d") {
      const dimKeys = ["eq5d_1", "eq5d_2", "eq5d_3", "eq5d_4", "eq5d_5", "__eq5dvas"];
      const ans = dimKeys.filter(k => session.answers[k] != null);
      completion = dimKeys.length ? ans.length / dimKeys.length : 0;
      total = 100;
      const vas = session.answers.__eq5dvas;
      score = vas != null ? vas : null;

    } else if (form === "psfs") {
      const acts = session.psfs || [];
      const filled = acts.filter(a => a.score != null);
      completion = filled.length >= 3 ? 1 : filled.length / 3;
      total = 10;
      score = filled.length > 0
        ? Math.round((filled.reduce((s, a) => s + a.score, 0) / filled.length) * 10) / 10
        : null;
    }

    return { score, total, completion, unit };
  }

  window.RT = window.RT || {};
  Object.assign(window.RT, {
    useRoute, navigate, useScaleSession, computeScore,
    TopBar, Footer,
    formatDate, formatDateTime, ageFrom, interpret
  });
})();
