// About Panel — slide-in side panel (NOT a modal). Referenceable disclosure.
// Sections per PRD:
//  1. What this prototype does
//  2. What it doesn't do
//  3. Diagnosis depth tiers
//  4. Calculation methods + citation library
//  5. AI copilot behavior (3 dials, scope)
//  6. Session and privacy
//  7. Known limitations and roadmap

const { useState: useStateAbout, useEffect: useEffectAbout, useRef: useRefAbout } = React;

const ABOUT_SECTIONS = [
  { id: "does",        label: "What this does" },
  { id: "doesnt",      label: "What it doesn't do" },
  { id: "tiers",       label: "Diagnosis depth tiers" },
  { id: "methods",     label: "Calculation methods" },
  { id: "copilot",     label: "Copilot behavior" },
  { id: "privacy",     label: "Session & privacy" },
  { id: "roadmap",     label: "Limitations & roadmap" },
];

function AboutPanel({ open, onClose, initialSection }) {
  const [active, setActive] = useStateAbout("does");
  const bodyRef = useRefAbout(null);

  useEffectAbout(() => {
    if (open && initialSection) {
      setActive(initialSection);
      // Scroll to that section after render
      requestAnimationFrame(() => {
        const el = document.getElementById(`about-sec-${initialSection}`);
        if (el && bodyRef.current) {
          bodyRef.current.scrollTop = el.offsetTop - 12;
        }
      });
    }
  }, [open, initialSection]);

  // Esc to close
  useEffectAbout(() => {
    if (!open) return;
    function onKey(e) { if (e.key === "Escape") onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // Track which section is in view as user scrolls
  useEffectAbout(() => {
    if (!open || !bodyRef.current) return;
    const el = bodyRef.current;
    function onScroll() {
      const top = el.scrollTop + 24;
      let current = "does";
      for (const sec of ABOUT_SECTIONS) {
        const node = document.getElementById(`about-sec-${sec.id}`);
        if (node && node.offsetTop <= top) current = sec.id;
      }
      setActive(current);
    }
    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, [open]);

  function jumpTo(id) {
    setActive(id);
    const el = document.getElementById(`about-sec-${id}`);
    if (el && bodyRef.current) bodyRef.current.scrollTop = el.offsetTop - 12;
  }

  return (
    <>
      <div className={`about-overlay ${open ? "open" : ""}`} onClick={onClose} aria-hidden="true" />
      <aside className={`about-panel ${open ? "open" : ""}`} aria-label="About this prototype" aria-hidden={!open}>
        <header className="about-head">
          <div>
            <div className="about-eyebrow">About this prototype</div>
            <h2 className="about-title">Basis</h2>
          </div>
          <button type="button" className="icon-btn" aria-label="Close" onClick={onClose}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
          </button>
        </header>

        <nav className="about-nav" aria-label="Section navigation">
          {ABOUT_SECTIONS.map(s => (
            <button
              key={s.id}
              type="button"
              className={`about-nav-item ${active === s.id ? "active" : ""}`}
              onClick={() => jumpTo(s.id)}
            >
              {s.label}
            </button>
          ))}
        </nav>

        <div className="about-body" ref={bodyRef}>
          <section id="about-sec-does" className="about-section">
            <h3>What this prototype does</h3>
            <ul>
              <li>Captures structured patient inputs (demographics, anthropometrics, diagnosis, comorbidities, activity, food security, labs).</li>
              <li>Calculates energy needs (Mifflin-St Jeor or Harris-Benedict, with activity, stress, and caloric adjustment), protein (diagnosis-driven g/kg with geriatric floor and adjusted body weight in obesity), and fluids (per-kcal or per-kg).</li>
              <li>Drafts IDNT-aligned PES statements, diagnosis- and comorbidity-aware interventions, structured monitoring sections, and a cleanly rendered note.</li>
              <li>Provides a conversational copilot in the rail that reads and updates the chart in natural language — no slash commands.</li>
            </ul>
          </section>

          <section id="about-sec-doesnt" className="about-section">
            <h3>What it doesn't do (yet)</h3>
            <ul>
              <li>No EHR integration. No patient lookup. No persistent storage of any kind.</li>
              <li>No general clinical Q&A. The copilot is scoped to this patient's chart.</li>
              <li>No drug interactions, no diagnostic suggestions outside IDNT problem terminology, no lab interpretation beyond the inputs you provide.</li>
              <li>No multi-patient workflows, voice input, or template export.</li>
              <li>No real PHI handling — this is a prototype, not a production tool.</li>
            </ul>
          </section>

          <section id="about-sec-tiers" className="about-section">
            <h3>Diagnosis depth tiers</h3>
            <p>Different diagnoses get different treatment based on how prescriptive the evidence is.</p>
            <div className="tier-grid">
              <div className="tier-card tier-deep">
                <div className="tier-label">Deep logic</div>
                <ul>
                  <li><strong>CKD (non-dialysis, stages 3–5)</strong> — KDOQI 2020 protein restriction, GFR-aware, sodium/potassium/phosphorus monitoring.</li>
                  <li><strong>Obesity / Weight management</strong> — Adjusted body weight by default, energy-deficit defaults, satiety-distributed protein.</li>
                </ul>
              </div>
              <div className="tier-card tier-standard">
                <div className="tier-label">Standard defaults</div>
                <ul>
                  <li><strong>Type 2 Diabetes</strong> — Carb consistency, plate method, low-GI emphasis.</li>
                  <li><strong>Wound healing / Pressure injury</strong> — Elevated protein 1.2–1.5 g/kg, micronutrient focus.</li>
                  <li><strong>Sarcopenia / Elderly malnutrition</strong> — Distributed protein ≥25–30 g/meal, energy-density.</li>
                  <li><strong>Healthy adult / Maintenance</strong> — Vegetable-forward plate, whole grains, hydration.</li>
                </ul>
              </div>
              <div className="tier-card tier-fallback">
                <div className="tier-label">General fallback</div>
                <ul>
                  <li><strong>Other (free text)</strong> — Plate method, balanced macros, hydration. No diagnosis-specific logic.</li>
                </ul>
              </div>
            </div>
          </section>

          <section id="about-sec-methods" className="about-section">
            <h3>Calculation methods</h3>

            <div className="method-block">
              <h4>Energy</h4>
              <p>BMR × activity multiplier × stress factor + caloric adjustment.</p>
              <ul>
                <li><strong>Mifflin-St Jeor (default)</strong> — F: (10×kg) + (6.25×cm) − (5×age) − 161 · M: same +5.</li>
                <li><strong>Harris-Benedict (revised 1984)</strong> — Older equation; tends to slightly overestimate.</li>
                <li><strong>Activity multipliers</strong> — Sedentary 1.2 · Light 1.375 · Moderate 1.55 · Very 1.725 · Extra 1.9.</li>
              </ul>
            </div>

            <div className="method-block">
              <h4>Protein (diagnosis-driven)</h4>
              <ul>
                <li>CKD non-dialysis: 0.55–0.60 g/kg (KDOQI)</li>
                <li>Obesity: 1.2–1.5 g/kg adjusted body weight</li>
                <li>Wound healing: 1.2–1.5 g/kg</li>
                <li>T2DM: 1.0–1.5 g/kg actual</li>
                <li>Healthy / elderly maintenance: 0.8–1.0 g/kg with a 1.0 g/kg floor at age ≥65 (ESPEN)</li>
              </ul>
              <p>Adjusted body weight = IBW + 0.25 × (actual − IBW). Applied automatically when BMI ≥30 with an obesity diagnosis; toggleable.</p>
            </div>

            <div className="method-block">
              <h4>Fluids</h4>
              <p>1 mL per kcal of energy needs, or 30–35 mL/kg actual body weight.</p>
            </div>

            <div className="method-block">
              <h4>Citation library</h4>
              <ul className="cite-list">
                <li>Mifflin MD, et al. <em>Am J Clin Nutr</em> 1990;51(2):241–7.</li>
                <li>KDOQI Clinical Practice Guideline for Nutrition in CKD: 2020 Update.</li>
                <li>Academy of Nutrition and Dietetics Adult Weight Management EBNPG.</li>
                <li>ASPEN Clinical Guidelines.</li>
                <li>NPIAP Clinical Practice Guideline (Pressure Injury).</li>
                <li>ESPEN Guideline on Clinical Nutrition and Hydration in Geriatrics.</li>
                <li>Academy Position Paper on Older Adults.</li>
                <li>ASPEN/Academy Consensus on Adult Malnutrition.</li>
                <li>Academy Diabetes EBNPG.</li>
                <li>Academy IDNT Reference Manual.</li>
              </ul>
              <p className="muted">The copilot cites only from this library. If a recommendation is general principle, it says so. It will not invent references.</p>
            </div>
          </section>

          <section id="about-sec-copilot" className="about-section">
            <h3>AI copilot behavior</h3>
            <p>The copilot is conversational and chart-aware. It runs three calibrated behaviors:</p>

            <div className="dial">
              <div className="dial-num">Dial 1</div>
              <div className="dial-body">
                <strong>Always precise.</strong> When inputs are ambiguous (a weight number with no unit, "CKD" with no stage, "active" without a level), the copilot asks once with chip choices — and remembers your answer for the rest of the session.
              </div>
            </div>

            <div className="dial">
              <div className="dial-num">Dial 2</div>
              <div className="dial-body">
                <strong>Balanced nudges.</strong> Only nudges when a calculation you asked for is blocked by missing required data (e.g., energy needs activity level). It doesn't nag about optional fields.
              </div>
            </div>

            <div className="dial">
              <div className="dial-num">Dial 3</div>
              <div className="dial-body">
                <strong>Conservative observations.</strong> Exactly five hardcoded clinical observations: BMI extremes, significant unintentional weight loss, CKD without GFR, conflicting activity-vs-notes, and adjusted body weight applies. No freelance "tips."
              </div>
            </div>

            <h4>Scope</h4>
            <p><strong>Will respond to</strong> chart updates, calculation explanations, documentation drafting, and meta questions about the prototype.</p>
            <p><strong>Will not respond to</strong> general clinical questions beyond the current patient, drug interactions, or diagnostic recommendations beyond IDNT terminology.</p>

            <h4>Voice</h4>
            <p>Warm professional. Sounds like a thoughtful colleague — not a form, not a chatbot.</p>
          </section>

          <section id="about-sec-privacy" className="about-section">
            <h3>Session and privacy</h3>
            <ul>
              <li><strong>In-memory only.</strong> All chart data lives in your browser tab. Nothing is saved or transmitted.</li>
              <li><strong>No persistence.</strong> Closing the tab or hitting "New session" clears everything.</li>
              <li><strong>No PHI.</strong> Don't enter real patient identifiers — the prototype doesn't need them and isn't built to handle them.</li>
              <li><strong>No analytics or logging.</strong></li>
            </ul>
          </section>

          <section id="about-sec-roadmap" className="about-section">
            <h3>Known limitations and roadmap</h3>
            <ul>
              <li><strong>Voice input</strong> — planned for a later round.</li>
              <li><strong>EHR templates</strong> — copy-out works today; structured export (FHIR / templated note) is roadmap.</li>
              <li><strong>Lab interpretation</strong> — labs are accepted as freeform; structured parsing and trending is roadmap.</li>
              <li><strong>Multi-visit history</strong> — no persistence yet, so no longitudinal view.</li>
              <li><strong>Pediatric / pregnancy</strong> — out of scope for this prototype; adult-only formulas.</li>
              <li><strong>Renal replacement therapy</strong> — dialysis-specific protein targets are not implemented.</li>
            </ul>
          </section>

          <div className="about-foot">
            <span className="badge">Prototype</span>
            <span>Outputs may contain errors. The RD is responsible for reviewing all content before clinical use.</span>
          </div>
        </div>
      </aside>
    </>
  );
}

window.AboutPanel = AboutPanel;
window.ABOUT_SECTIONS = ABOUT_SECTIONS;
