// The phone app: one web page stored inside the ESP32.  Open it in the phone's browser
// (http://pillreminder.local or the IP shown on the LCD) and use "Add to Home screen".
#pragma once

const char PAGE[] PROGMEM = R"html(<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#3A7D74">
<title>Smart Pill Reminder</title>
<style>
:root{--teal:#3A7D74;--teal-d:#2C625B;--paper:#EEF3F1;--card:#fff;--ink:#1E2A2B;--muted:#5D6B6A;--line:#D9D4C7;--amber:#B87503;--red:#B83A2E;--ok:#2E7D4F}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.45 "Segoe UI",Tahoma,"Noto Sans Arabic","Geeza Pro",sans-serif}
header{background:var(--teal);color:#fff;padding:14px 16px;display:flex;align-items:center;gap:12px}
header h1{font-size:18px;margin:0;flex:1}
#clock{font-variant-numeric:tabular-nums}
.lang{background:none;border:1px solid rgba(255,255,255,.7);color:#fff;border-radius:6px;padding:5px 10px;font:inherit}
nav{display:flex;background:#fff;border-bottom:1px solid var(--line);position:sticky;top:0}
nav button{flex:1;padding:12px 4px;border:0;background:none;font:inherit;color:var(--muted);border-bottom:3px solid transparent}
nav button.on{color:var(--teal-d);border-bottom-color:var(--teal);font-weight:600}
main{max-width:560px;margin:0 auto;padding:16px}
section{display:none}section.on{display:block}
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px;margin-bottom:14px}
h2{font-size:18px;margin:0 0 6px}
.state{font-size:22px;font-weight:700;margin:0 0 4px}
.state.alert{color:var(--amber)}.state.bad{color:var(--red)}.state.ok{color:var(--ok)}
.sub,.hint{color:var(--muted);margin:0}.hint{font-size:14px}
.row{display:flex;gap:10px;flex-wrap:wrap}
.btn{flex:1 1 140px;min-height:48px;padding:12px;border-radius:8px;border:1px solid var(--teal);background:#fff;color:var(--teal-d);font:inherit;font-weight:600}
.btn.main{background:var(--teal);color:#fff}.btn.warn{border-color:var(--red);color:var(--red)}
.btn:active{transform:scale(.98)}
label{display:block;font-weight:600;margin:14px 0 4px}
input,select{font:inherit}
input[type=time],input[type=text],input[type=number],select{width:100%;padding:10px;border:1px solid var(--line);border-radius:6px;background:#fff}
input[type=range]{width:100%}
.dose{display:grid;grid-template-columns:28px 1fr 1.3fr;gap:8px;align-items:center;margin-bottom:10px}
.dose input[type=checkbox],#rev{width:22px;height:22px}
ul.log{list-style:none;padding:0;margin:0}
ul.log li{padding:10px 0;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;gap:8px}
.tag{font-size:13px;padding:2px 8px;border-radius:999px;background:#E6EFED;color:var(--teal-d);white-space:nowrap}
.tag.M,.tag.S,.tag.E{background:#F6E1DE;color:var(--red)}.tag.T{background:#E1F0E6;color:var(--ok)}
#left,#clock,#ip{direction:ltr;unicode-bidi:isolate}
.sensors{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:10px;font-size:14px}
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;background:#bbb;margin-inline-end:6px}.dot.on{background:var(--ok)}
.toast{position:fixed;left:50%;bottom:20px;transform:translateX(-50%);background:var(--ink);color:#fff;padding:10px 16px;border-radius:8px;opacity:0;transition:opacity .2s;pointer-events:none}
.toast.on{opacity:1}
</style></head><body>
<header><h1 data-t="title">Smart Pill Reminder</h1><span id="clock">--:--</span><button class="lang" id="lang">عربي</button></header>
<nav><button data-tab="today" class="on" data-t="today">Today</button><button data-tab="sched" data-t="sched">Schedule</button><button data-tab="set" data-t="set">Settings</button><button data-tab="hist" data-t="hist">History</button></nav>
<main>
<section id="today" class="on">
 <div class="card"><p class="state" id="state">...</p><p class="sub" id="next"></p></div>
 <div class="card" style="text-align:center"><svg id="ring" viewBox="-110 -110 220 220" width="230" height="230" role="img" aria-label="carousel"></svg>
  <p class="sub"><span data-t="left">Doses left</span>: <b id="left">-</b></p></div>
 <div class="card"><div class="row">
  <button class="btn main" data-do="taken" data-t="b_taken">I took my pills</button>
  <button class="btn" data-do="dispense" data-t="b_disp">Drop a dose now</button>
  <button class="btn" data-do="demo" data-t="b_demo">Demo: dose in 1 minute</button>
  <button class="btn" data-do="sound" data-t="b_sound">Test sound</button>
  <button class="btn warn" data-do="stop" data-t="b_stop">Stop alarm</button></div></div>
</section>
<section id="sched"><div class="card"><h2 data-t="sched">Schedule</h2>
 <p class="hint" data-t="sched_hint">Up to 4 doses a day. One compartment drops at each time.</p><div id="doses" style="margin-top:12px"></div>
 <button class="btn main" id="saveSched" data-t="save">Save</button></div></section>
<section id="set">
 <div class="card"><h2 data-t="sound">Sound and alerts</h2>
  <label for="vol"><span data-t="vol">Volume</span>: <b id="volv"></b></label><input type="range" id="vol" min="0" max="30">
  <label for="voice" data-t="voice">Voice language</label><select id="voice"><option value="1">العربية</option><option value="0">English</option></select>
  <label for="rep" data-t="rep">Repeat the alarm every (seconds)</label><input type="number" id="rep" min="10" max="600">
  <label for="miss" data-t="miss">Mark the dose missed after (minutes)</label><input type="number" id="miss" min="1" max="240">
  <label for="ntfy" data-t="ntfy">Family phone alerts (ntfy topic)</label><input type="text" id="ntfy" maxlength="60">
  <p class="hint" data-t="ntfy_hint">Install the free ntfy app and subscribe to the same topic name. Needs home WiFi with internet.</p>
  <button class="btn main" id="saveSet" data-t="save" style="margin-top:12px">Save</button></div>
 <div class="card"><h2 data-t="refill">Refill the carousel</h2>
  <p class="hint" data-t="refill_hint">1. Press "Go to H". 2. Lift the lid by its two side notches and put one dose in each slot 1 to 14 (H has a roof). 3. Press "Refill done".</p>
  <div class="row" style="margin-top:12px"><button class="btn" data-do="home" data-t="b_home">Go to H</button><button class="btn main" data-do="refilled" data-t="b_refilled">Refill done</button></div></div>
 <div class="card"><h2 data-t="motor">Motor and sensors</h2>
  <div class="sensors"><span><i class="dot" id="dtilt"></i><span data-t="s_tilt">Cup at full tilt</span></span><span><i class="dot" id="dhome"></i><span data-t="s_home">Home switch pressed</span></span><span><i class="dot" id="drtc"></i><span data-t="s_rtc">Clock module connected</span></span></div>
  <p class="hint" style="margin-top:8px" data-t="tilt_hint">Push the cup to its stop: "Cup at full tilt" must light there and nowhere before.</p>
  <label for="hoff" data-t="hoff">Fine-tune the H position (steps)</label><input type="number" id="hoff" min="-400" max="400">
  <label for="spr" data-t="spr">Steps for one full turn</label><input type="number" id="spr" min="2000" max="5000">
  <label><input type="checkbox" id="rev"> <span data-t="rev">Turn the other way</span></label>
  <div class="row" style="margin-top:12px"><button class="btn main" id="saveMotor" data-t="save">Save</button>
  <button class="btn warn" data-do="calib" data-t="b_calib">Find H (empty carousel only)</button></div>
  <p class="hint" style="margin-top:10px">IP: <span id="ip"></span></p></div>
</section>
<section id="hist"><div class="card"><h2 data-t="hist">History</h2><ul class="log" id="log"></ul></div></section>
</main><div class="toast" id="toast" role="status"></div>
<script>
const T={en:{title:"Smart Pill Reminder",today:"Today",sched:"Schedule",set:"Settings",hist:"History",left:"Doses left",
b_taken:"I took my pills",b_disp:"Drop a dose now",b_demo:"Demo: dose in 1 minute",b_sound:"Test sound",b_stop:"Stop alarm",
sched_hint:"Up to 4 doses a day. One compartment drops at each time.",save:"Save",sound:"Sound and alerts",vol:"Volume",voice:"Voice language",
rep:"Repeat the alarm every (seconds)",miss:"Mark the dose missed after (minutes)",ntfy:"Family phone alerts (ntfy topic)",
ntfy_hint:"Install the free ntfy app and subscribe to the same topic name. Needs home WiFi with internet.",refill:"Refill the carousel",
refill_hint:"1. Press \"Go to H\". 2. Lift the lid by its two side notches and put one dose in each slot 1 to 14 (H has a roof). 3. Press \"Refill done\".",
b_home:"Go to H",b_refilled:"Refill done",motor:"Motor and sensors",s_tilt:"Cup at full tilt",tilt_hint:"Push the cup to its stop: \"Cup at full tilt\" must light there and nowhere before.",s_home:"Home switch pressed",s_rtc:"Clock module connected",
hoff:"Fine-tune the H position (steps)",spr:"Steps for one full turn",rev:"Turn the other way",b_calib:"Find H (empty carousel only)",
st_alert:"Time to take your pills!",st_alert_sub:"Push the bottom of the cup all the way to its stop: the pills slide into your hand.",
st_refill:"Please refill the carousel",st_wait:"The last dose is still in the cup",st_ok:"All good",st_time:"Clock not set",
next:"Next dose",none:"No dose times set",D:"Dose dropped",T:"Taken",M:"Missed",S:"Not dropped: last dose still in the cup",R:"Refilled",E:"Home switch not found",
slot:"slot",done:"Done",empty:"The carousel is empty. Refill first.",waiting:"Take the pills in the cup first.",nothome:"Press \"Go to H\" first.",
notime:"Set the clock first.",label:"Name (Morning...)"},
ar:{title:"منبه الدواء الذكي",today:"اليوم",sched:"المواعيد",set:"الإعدادات",hist:"السجل",left:"الجرعات المتبقية",
b_taken:"أخذت الدواء",b_disp:"إنزال جرعة الآن",b_demo:"تجربة: جرعة بعد دقيقة",b_sound:"تجربة الصوت",b_stop:"إيقاف المنبه",
sched_hint:"حتى ٤ جرعات في اليوم. تنزل خانة واحدة في كل موعد.",save:"حفظ",sound:"الصوت والتنبيهات",vol:"مستوى الصوت",voice:"لغة الصوت",
rep:"كرر التنبيه كل (ثانية)",miss:"اعتبر الجرعة فائتة بعد (دقيقة)",ntfy:"تنبيهات لهاتف العائلة (اسم موضوع ntfy)",
ntfy_hint:"ثبّت تطبيق ntfy المجاني واشترك بنفس الاسم. يحتاج واي فاي المنزل مع إنترنت.",refill:"تعبئة القرص",
refill_hint:"١. اضغط «اذهب إلى H». ٢. ارفع الغطاء من فتحتيه الجانبيتين وضع جرعة واحدة في كل خانة من ١ إلى ١٤ (الخانة H مغطاة). ٣. اضغط «انتهت التعبئة».",
b_home:"اذهب إلى H",b_refilled:"انتهت التعبئة",motor:"المحرك والحساسات",s_tilt:"الكوب مائل بالكامل",tilt_hint:"ادفع الكوب حتى يتوقف: يجب أن تضيء «الكوب مائل بالكامل» عند التوقف فقط، لا قبله.",s_home:"مفتاح البداية مضغوط",s_rtc:"وحدة الساعة متصلة",
hoff:"ضبط دقيق لموضع H (خطوات)",spr:"عدد الخطوات للدورة الكاملة",rev:"اعكس اتجاه الدوران",b_calib:"ابحث عن H (والقرص فارغ فقط)",
st_alert:"حان موعد الدواء!",st_alert_sub:"ادفع أسفل الكوب حتى يتوقف لتنزل الحبوب في يدك.",
st_refill:"يرجى تعبئة القرص",st_wait:"الجرعة السابقة ما زالت في الكوب",st_ok:"كل شيء تمام",st_time:"الساعة غير مضبوطة",
next:"الجرعة القادمة",none:"لا توجد مواعيد",D:"نزلت جرعة",T:"أُخذت",M:"فائتة",S:"لم تنزل: الجرعة السابقة في الكوب",R:"تمت التعبئة",E:"لم يُعثر على مفتاح البداية",
slot:"خانة",done:"تم",empty:"القرص فارغ. عبّئه أولاً.",waiting:"خذ الحبوب من الكوب أولاً.",nothome:"اضغط «اذهب إلى H» أولاً.",
notime:"اضبط الساعة أولاً.",label:"اسم (صباح...)"}};
let lang="en",S=null,filled=false,synced=false;
try{lang=localStorage.getItem("lang")||"en"}catch(e){}
const $=q=>document.querySelector(q),t=k=>(T[lang]&&T[lang][k])||T.en[k]||k;
function toast(m){const e=$("#toast");e.textContent=m;e.classList.add("on");setTimeout(()=>e.classList.remove("on"),2200)}
function post(url,data){return fetch(url,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(data)}).then(r=>r.json()).then(j=>{toast(j.msg=="ok"?t("done"):t(j.msg));setTimeout(load,600)}).catch(()=>toast("..."))}
function applyLang(){document.documentElement.lang=lang;document.documentElement.dir=lang=="ar"?"rtl":"ltr";
 document.querySelectorAll("[data-t]").forEach(e=>e.textContent=t(e.dataset.t));$("#lang").textContent=lang=="ar"?"English":"عربي";
 document.querySelectorAll(".dose input[type=text]").forEach(e=>e.placeholder=t("label"));if(S)render()}
$("#lang").onclick=()=>{lang=lang=="ar"?"en":"ar";try{localStorage.setItem("lang",lang)}catch(e){}applyLang()};
document.querySelectorAll("nav button").forEach(b=>b.onclick=()=>{document.querySelectorAll("nav button,section").forEach(x=>x.classList.remove("on"));b.classList.add("on");$("#"+b.dataset.tab).classList.add("on")});
document.querySelectorAll("[data-do]").forEach(b=>b.onclick=()=>post("/api/action",{do:b.dataset.do}));
const p2=n=>String(n).padStart(2,"0"),hm=s=>{const d=new Date(s*1000);return p2(d.getHours())+":"+p2(d.getMinutes())};
function sector(r0,r1,a0,a1){const P=(r,a)=>[r*Math.cos(a*Math.PI/180),-r*Math.sin(a*Math.PI/180)].map(v=>v.toFixed(1)).join(" ");
 return `M${P(r1,a0)}A${r1} ${r1} 0 0 0 ${P(r1,a1)}L${P(r0,a1)}A${r0} ${r0} 0 0 1 ${P(r0,a0)}Z`}
function ring(){let g="";const n=S.slots,w=360/n;
 for(let k=0;k<n;k++){const mid=-90-w*(k-S.pos),fill=k==0?"#E4E1D8":k<S.pos?"#F4F1EA":k==S.pos?"#E9B949":"#3A7D74";
  g+=`<path d="${sector(40,100,mid-w/2+1,mid+w/2-1)}" fill="${fill}" stroke="#D9D4C7"/>`;
  const x=70*Math.cos(mid*Math.PI/180),y=-70*Math.sin(mid*Math.PI/180);
  g+=`<text x="${x.toFixed(1)}" y="${(y+4).toFixed(1)}" text-anchor="middle" style="fill:${k>S.pos?"#fff":"#1E2A2B"}">${k==0?"H":k}</text>`}
 g+=`<path d="M-8 106 L8 106 L0 96 Z" fill="#B87503"/>`;$("#ring").innerHTML=g}
function render(){const st=$("#state"),nx=$("#next");let cls="ok",txt=t("st_ok"),sub="";
 if(!S.timeOk){cls="bad";txt=t("st_time")}
 else if(S.state=="alert"){cls="alert";txt=t("st_alert");sub=t("st_alert_sub")}
 else if(S.state=="refill"){cls="bad";txt=t("st_refill")}
 else if(S.waiting){cls="bad";txt=t("st_wait")}
 if(!sub)sub=S.next?t("next")+": "+S.next+(S.nextLabel?" ("+S.nextLabel+")":""):t("none");
 st.className="state "+cls;st.textContent=txt;nx.textContent=sub;$("#left").textContent=(S.slots-1-S.pos)+" / "+(S.slots-1);
 $("#dtilt").classList.toggle("on",!!S.tilt);$("#dhome").classList.toggle("on",!!S.home);$("#drtc").classList.toggle("on",!!S.rtc);$("#ip").textContent=S.ip;ring();
 $("#log").innerHTML=S.log.map(e=>{const d=new Date(e.t*1000);return `<li><span>${p2(d.getDate())}/${p2(d.getMonth()+1)} ${hm(e.t)} · ${t("slot")} ${e.s}</span><span class="tag ${e.k}">${t(e.k)}</span></li>`}).join("")}
function fill(){$("#doses").innerHTML=S.doses.map((d,i)=>`<div class="dose"><input type="checkbox" id="on${i}" ${d.on?"checked":""} aria-label="on"><input type="time" id="t${i}" value="${d.t}"><input type="text" id="l${i}" maxlength="12" value="${d.l.replace(/"/g,"&quot;")}" placeholder="${t("label")}"></div>`).join("");
 $("#vol").value=S.vol;$("#volv").textContent=S.vol;$("#voice").value=S.arabic?"1":"0";$("#rep").value=S.rep;$("#miss").value=S.miss;$("#ntfy").value=S.ntfy;
 $("#hoff").value=S.hoff;$("#spr").value=S.spr;$("#rev").checked=!!S.rev;filled=true}
$("#vol").oninput=e=>$("#volv").textContent=e.target.value;
$("#saveSched").onclick=()=>{const d={};for(let i=0;i<4;i++){d["on"+i]=$("#on"+i).checked?1:0;d["t"+i]=$("#t"+i).value||"00:00";d["l"+i]=$("#l"+i).value}post("/api/schedule",d)};
$("#saveSet").onclick=()=>post("/api/settings",{vol:$("#vol").value,arabic:$("#voice").value,rep:$("#rep").value,miss:$("#miss").value,ntfy:$("#ntfy").value.trim()});
$("#saveMotor").onclick=()=>post("/api/motor",{hoff:$("#hoff").value,spr:$("#spr").value,rev:$("#rev").checked?1:0});
function load(){fetch("/api/status").then(r=>r.json()).then(j=>{S=j;const now=Math.round(Date.now()/1000);
 if(!synced&&(!S.timeOk||Math.abs(S.now-now)>60)){synced=true;post("/api/time",{epoch:now})}
 if(!filled)fill();render()}).catch(()=>{})}
setInterval(()=>{const d=new Date();$("#clock").textContent=p2(d.getHours())+":"+p2(d.getMinutes())},1000);
applyLang();load();setInterval(load,3000);
</script></body></html>)html";
