// ============================================================
// AREA PAZIENTE — il paziente vede il proprio piano e può
// apportare modifiche (cambio pasto, comandi a parole), che restano
// nei limiti indicati dal medico. Se ci sono due settimane (A/B) si
// alternano automaticamente in base alla settimana del calendario.
// ============================================================
function isoWeekNum(d) {
  const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  const day = t.getUTCDay() || 7;
  t.setUTCDate(t.getUTCDate() + 4 - day);
  const ys = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
  return Math.ceil((((t - ys) / 86400000) + 1) / 7);
}
const currentParity = () => (isoWeekNum(new Date()) % 2 === 0 ? "A" : "B");

const PASTO_LABEL = { colazione: "Colazione", pranzo: "Pranzo", cena: "Cena" };

// Scheda completa del piatto: cottura, ingredienti con quantità, passaggi di
// preparazione e valori nutrizionali.
function PatientMealDetail({ recipe, onClose }) {
  const { FOOD_BY_ID } = window.NefroData;
  const Rx = window.NefroRx;
  const t = window.NefroEngine.totals(recipe);
  const NUTR = ["calorie", "proteine", "potassio", "fosforo", "sodio", "liquidi", "fibre", "grassi_saturi"];
  const steps = (recipe.procedimento || "").split("\n").map((s) => s.trim().replace(/^\d+[\.\)]\s*/, "")).filter(Boolean);
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="pz-modal" onClick={(e) => e.stopPropagation()}>
        <div className="pz-modal-head">
          <div>
            <span className="pz-meal-pasto">{PASTO_LABEL[recipe.pasto] || recipe.pasto}</span>
            <h3 className="pz-modal-title">{recipe.nome}</h3>
            {recipe.cottura && <div className="pz-modal-cottura"><Icon name="flame" size={14} /> Metodo di cottura: <b>{recipe.cottura}</b></div>}
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="pz-modal-body">
          <div className="pz-sec-title"><Icon name="leaf" size={14} /> Ingredienti e quantità</div>
          <ul className="pz-det-ings">
            {recipe.ingredienti.map((i, k) => {
              const f = FOOD_BY_ID[i.id];
              const cott = i.cottura || (f && f.cottura);
              return (
                <li key={k}>
                  <span className="pz-det-ing-name">{f ? f.nome : i.id}</span>
                  <span className="pz-det-ing-q">{i.grammi} g{cott ? <em> · {cott}</em> : null}</span>
                </li>
              );
            })}
          </ul>
          <div className="pz-sec-title"><Icon name="bowl" size={14} /> Come si prepara</div>
          {steps.length ?
            <ol className="pz-steps">{steps.map((s, k) => <li key={k}>{s}</li>)}</ol> :
            <p className="pz-empty-note">Preparazione semplice: pesa gli ingredienti secondo le quantità indicate{recipe.cottura ? ` e cuoci ${recipe.cottura}` : ""}.</p>}
          <div className="pz-sec-title"><Icon name="droplet" size={14} /> Valori nutrizionali del piatto</div>
          <div className="pz-nutri">
            {NUTR.map((n) => {
              const m = (Rx && Rx.NUTRIENT_META[n]) || { label: n, unit: "" };
              return (
                <div key={n} className="pz-nutri-cell">
                  <span className="pz-nutri-val">{Math.round((t[n] || 0) * 10) / 10}<i>{m.unit}</i></span>
                  <span className="pz-nutri-lab">{m.label}{m.a3 ? " *" : ""}</span>
                </div>
              );
            })}
          </div>
          <p className="pz-nutri-note">* Valori stimati, indicativi. In caso di dubbi segui le indicazioni del tuo medico.</p>
        </div>
      </div>
    </div>
  );
}

function PatientMeal({ recipe, editing, onChange }) {
  const { FOOD_BY_ID } = window.NefroData;
  const [detail, setDetail] = useState(false);
  if (!recipe) return null;
  const t = window.NefroEngine.totals(recipe);
  return (
    <div className="pz-meal">
      <div className="pz-meal-head">
        <span className="pz-meal-pasto">{PASTO_LABEL[recipe.pasto] || recipe.pasto}</span>
        {recipe.cottura && <span className="pz-meal-cottura">{recipe.cottura}</span>}
        {editing && <button className="pz-change" onClick={onChange} title="Proponi un altro pasto"><Icon name="refresh" size={12} /> Cambia</button>}
      </div>
      <button className="pz-meal-name pz-meal-name-btn" onClick={() => setDetail(true)} title="Vedi ingredienti, cottura e preparazione">{recipe.nome}</button>
      <ul className="pz-ings">
        {recipe.ingredienti.map((i, k) => {
          const f = FOOD_BY_ID[i.id];
          return <li key={k}><span>{f ? f.nome : i.id}</span><b>{i.grammi} g{i.cottura ? " · " + i.cottura : ""}</b></li>;
        })}
      </ul>
      <div className="pz-meal-foot">
        <span className="pz-micro"><i>K</i>{Math.round(t.potassio)}</span>
        <span className="pz-micro"><i>P</i>{Math.round(t.fosforo)}</span>
        <span className="pz-micro"><i>Na</i>{Math.round(t.sodio)}</span>
        <span className="pz-micro"><i>kcal</i>{Math.round(t.calorie)}</span>
        <button className="pz-proc-toggle" onClick={() => setDetail(true)}>
          <Icon name="bowl" size={13} /> Dettagli e preparazione
        </button>
      </div>
      {detail && <PatientMealDetail recipe={recipe} onClose={() => setDetail(false)} />}
    </div>
  );
}

function PatientApp() {
  const { MY_PATIENT: patient, MY_WEEK } = window.NefroData;
  const E = window.NefroEngine;

  const [plan, setPlan] = useState(() => ({ giorni: MY_WEEK?.giorni || null, giorniB: MY_WEEK?.giorniB || null }));
  const hasB = Array.isArray(plan.giorniB) && plan.giorniB.length > 0;
  const thisWeek = currentParity();
  const [active, setActive] = useState(() => (hasB ? currentParity() : "A"));
  const [editing, setEditing] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [saving, setSaving] = useState(false);
  const [input, setInput] = useState("");
  const [note, setNote] = useState(null);

  const giorni = active === "B" ? plan.giorniB : plan.giorni;
  const setGiorni = (g) => { setPlan((p) => ({ ...p, [active === "B" ? "giorniB" : "giorni"]: g })); setDirty(true); };

  const validation = giorni && window.NefroRx ? E.validateWeek(giorni, patient) : [];
  const overDays = validation.filter((d) => d.worst === "over");

  const changeMeal = (dayId, pasto) => {
    const fresh = E.generateWeek(patient, Date.now() % 9999)[0][pasto];
    setGiorni(giorni.map((d) => d.id === dayId ? { ...d, [pasto]: { ...fresh } } : d));
    setNote(null);
  };
  const sendCmd = (text) => {
    const msg = text.trim(); if (!msg) return;
    const res = E.applyCommand(msg, giorni, patient);
    if (res.ok) setGiorni(res.week);
    setNote(res.message);
    setInput("");
  };
  const save = async () => {
    setSaving(true); setNote(null);
    try {
      await window.NefroAPI.saveMyWeek(plan.giorni, plan.giorniB);
      setDirty(false); setNote("Le tue modifiche sono state salvate.");
    } catch (e) { setNote("Salvataggio non riuscito: " + e.message); }
    finally { setSaving(false); }
  };
  const restore = async () => {
    try {
      const w = await window.NefroAPI.myWeek();
      setPlan({ giorni: w?.giorni || null, giorniB: w?.giorniB || null });
      setDirty(false); setNote("Ripristinato il piano del medico.");
    } catch (e) { setNote("Ripristino non riuscito: " + e.message); }
  };

  const changePassword = async () => {
    const pw = prompt("Nuova password (min 4 caratteri):");
    if (!pw) return;
    try { await window.NefroAPI.changeMyPassword(pw); alert("Password aggiornata."); }
    catch (e) { alert("Non riuscito: " + e.message); }
  };

  return (
    <div className="pz-app">
      <header className="pz-top">
        <div className="pz-top-brand">
          <div className="brand-mark"><Icon name="droplet" size={18} /></div>
          <div><div className="pz-top-title">Il mio piano alimentare</div>
            <div className="pz-top-sub">AtaMed · AULSS 7 — Nefrologia</div></div>
        </div>
        <div className="pz-top-right">
          <span className="pz-top-name"><Avatar nome={patient.nome} cognome={patient.cognome} hue={patient.avatarHue} size={34} /> {patient.nome} {patient.cognome}</span>
          <button className="btn btn-ghost" onClick={changePassword}>Password</button>
          <button className="btn btn-ghost" onClick={() => window.NefroAPI.logout()}><Icon name="x" size={15} /> Esci</button>
        </div>
      </header>

      <div className="pz-body">
        <div className="pz-toolbar">
          <p className="pz-intro" style={{ margin: 0 }}>
            {editing
              ? "Puoi cambiare un pasto o scrivere una richiesta a parole. Le proposte restano tra gli alimenti adatti a te. Ricorda di salvare."
              : "Piano preparato dal tuo medico. Puoi apportare qualche modifica con «Modifica il piano»."}
          </p>
          <div className="btn-row">
            {hasB &&
              <div className="seg" style={{ marginRight: 4 }} title="Le due settimane si alternano">
                {["A", "B"].map((w) => <button key={w} className={`seg-btn ${active === w ? "on" : ""}`} onClick={() => setActive(w)}>Sett. {w}{w === thisWeek ? " · questa" : ""}</button>)}
              </div>}
            {!editing ?
              <button className="btn btn-primary" onClick={() => setEditing(true)} disabled={!giorni}><Icon name="edit" size={15} /> Modifica il piano</button> :
              <>
                <button className="btn btn-ghost" onClick={restore}>Ripristina medico</button>
                <button className={`btn ${dirty ? "btn-primary" : "btn-ghost"}`} disabled={!dirty || saving} onClick={save}>
                  <Icon name="check" size={15} /> {saving ? "Salvataggio…" : dirty ? "Salva" : "Salvato"}
                </button>
                <button className="btn btn-ghost" onClick={() => setEditing(false)}>Chiudi</button>
              </>}
          </div>
        </div>

        {hasB && <p className="pz-week-hint"><Icon name="calendar" size={13} /> Il tuo piano ha due settimane che si alternano: <b>questa settimana</b> segui la <b>Settimana {thisWeek}</b>.</p>}

        {editing && note && <div className="pz-note">{note}</div>}
        {editing && overDays.length > 0 &&
          <div className="pz-warn"><Icon name="alert" size={14} /> Alcuni giorni ({overDays.map((d) => d.nome).join(", ")}) superano i limiti indicati dal medico. Puoi salvare comunque, ma conviene sistemarli o chiedere al medico.</div>}

        {editing &&
          <form className="pz-cmd" onSubmit={(e) => { e.preventDefault(); sendCmd(input); }}>
            <Icon name="wand" size={16} />
            <input placeholder="Es. «niente pesce», «più verdure a pranzo», «cambia la frutta a colazione»" value={input} onChange={(e) => setInput(e.target.value)} />
            <button type="submit" className="btn btn-ghost" disabled={!input.trim()}>Applica</button>
          </form>}

        {!giorni ?
          <div className="pz-empty">
            <div className="empty-orb"><Icon name="calendar" size={22} /></div>
            <p>Il tuo piano non è ancora disponibile.<br />Sarà visibile qui non appena il tuo medico lo avrà preparato e salvato.</p>
          </div> :
          <div className="pz-days">
            {giorni.map((g) => {
              const dt = E.dayTotals(g);
              return (
                <section key={g.id} className="pz-day">
                  <div className="pz-day-head">
                    <h3 className="pz-day-name">{g.nome}</h3>
                    <div className="pz-day-tot">
                      <span><i>K</i>{Math.round(dt.potassio)}</span>
                      <span><i>P</i>{Math.round(dt.fosforo)}</span>
                      <span><i>Na</i>{Math.round(dt.sodio)}</span>
                      <span><i>Prot</i>{Math.round(dt.proteine)}g</span>
                      <span><i>kcal</i>{Math.round(dt.calorie)}</span>
                    </div>
                  </div>
                  <div className="pz-meals">
                    {["colazione", "pranzo", "cena"].map((p) => <PatientMeal key={p} recipe={g[p]} editing={editing} onChange={() => changeMeal(g.id, p)} />)}
                  </div>
                </section>
              );
            })}
          </div>}
      </div>
    </div>
  );
}
window.PatientApp = PatientApp;
