const { useState, useEffect, useRef } = React;
const { createClient } = supabase;

// ── SUPABASE ──────────────────────────────────────────────────────────────────
const sb = createClient(window.ENV.SUPABASE_URL, window.ENV.SUPABASE_ANON_KEY);

// ── CONSTANTS ─────────────────────────────────────────────────────────────────
const TODAY = new Date().toISOString().split("T")[0];
const uid   = () => Math.random().toString(36).slice(2,9);
const fmtDate = d => { try{return new Date(d+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"});}catch{return d;}};
const getDaysInMonth    = (y,m) => new Date(y,m+1,0).getDate();
const getFirstDayOfWeek = (y,m) => new Date(y,m,1).getDay();
const dKey              = (y,m,d) => `${y}-${String(m+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`;

// ── THEME ─────────────────────────────────────────────────────────────────────
const T = {
  bg:"#080808",bg2:"#0f0f0f",card:"#141414",card2:"#1c1c1c",
  border:"rgba(255,255,255,0.08)",sep:"rgba(255,255,255,0.07)",
  w1:"#ffffff",w2:"rgba(255,255,255,0.88)",w3:"rgba(255,255,255,0.62)",
  w4:"rgba(255,255,255,0.32)",w5:"rgba(255,255,255,0.08)",
};
const GS = {filter:"grayscale(1) brightness(0.9)"};

// ── DATA ──────────────────────────────────────────────────────────────────────
const PROFILES = [
  {id:"dalton",  name:"Dalton",  emoji:"⚡",role:"dalton",sub:"Dad"  },
  {id:"stefanie",name:"Stefanie",emoji:"🌸",role:"adult", sub:"Mom"  },
  {id:"dash",    name:"Dash",    emoji:"🚀",role:"kid",   sub:"Age 9"},
  {id:"jett",    name:"Jett",    emoji:"🛩️",role:"kid",   sub:"Age 7"},
  {id:"rush",    name:"Rush",    emoji:"🦁",role:"tiny",  sub:"Age 5"},
  {id:"cruz",    name:"Cruz",    emoji:"🌟",role:"baby",  sub:"Age 1"},
];

const DEF_HABITS = {
  dalton:[{id:"vitamins",label:"Vitamins",e:"💊"},{id:"creatine",label:"Creatine",e:"⚡"},{id:"upEnemy",label:"Up Before Enemy",e:"⏰"},{id:"god",label:"GOD — Pray & Read",e:"✝️"},{id:"workout",label:"Workout",e:"🏋️"},{id:"bjj",label:"Jiu Jitsu",e:"🥋"},{id:"read",label:"Read",e:"📖"},{id:"water",label:"Water 80oz",e:"💧"}],
  adult: [{id:"god",label:"Pray & Read",e:"✝️"},{id:"water",label:"Drink Water",e:"💧"},{id:"vitamins",label:"Vitamins",e:"💊"},{id:"move",label:"Move / Exercise",e:"🏃"},{id:"read",label:"Read",e:"📖"}],
  dash:  [{id:"pray",label:"Pray & Read Bible",e:"🙏"},{id:"upEarly",label:"Wake Up Early",e:"⏰"},{id:"workout",label:"Workout",e:"🏋️"},{id:"read",label:"Read 20min",e:"📖"},{id:"water",label:"Water 60oz",e:"💧"},{id:"makeBed",label:"Make My Bed",e:"🛏️"},{id:"kind",label:"Be Kind",e:"💛"}],
  kid:   [{id:"brush",label:"Brush Teeth",e:"🦷"},{id:"pray",label:"Pray & Read Bible",e:"🙏"},{id:"makeBed",label:"Make My Bed",e:"🛏️"},{id:"chores",label:"Chores",e:"✅"},{id:"read",label:"Read 20min",e:"📖"},{id:"kind",label:"Be Kind",e:"💛"}],
  tiny:  [{id:"brush",label:"Brush Teeth",e:"🦷"},{id:"pray",label:"Say Prayers",e:"🙏"},{id:"kind",label:"Be Kind",e:"💛"}],
};

const DEF_CFG = {
  energyOpts:["Low","Normal","High"],
  moodOpts:["Grateful","Present","Confident","Uncertain","Anxious","Focused","Tired","Motivated","Peaceful","Heavy","Joyful","Overwhelmed"],
  influenceOpts:["Work","Family","Faith","Health","Finance","BJJ","Kids","Sleep"],
};
const KID_MOODS = ["😄 Great","🙂 Good","😐 Okay","😟 Not Great","😢 Hard Day"];
const WORKOUT_TYPES = ["Run","Lift","BJJ","Soccer","Bike","Swim","Walk","Other"];

const defHabitsFor = pid => {
  if(pid==="dash") return DEF_HABITS.dash;
  const role = PROFILES.find(p=>p.id===pid)?.role||"kid";
  return DEF_HABITS[role==="dalton"?"dalton":role]||[];
};

// ── SUPABASE STORE ────────────────────────────────────────────────────────────
const DB = {
  // Entries
  getEntry: async (pid, date) => {
    const {data} = await sb.from("entries").select("data").eq("profile_id",pid).eq("entry_date",date).single();
    return data?.data || null;
  },
  saveEntry: async (pid, date, entryData) => {
    await sb.from("entries").upsert({profile_id:pid, entry_date:date, data:entryData, updated_at:new Date().toISOString()},{onConflict:"profile_id,entry_date"});
  },
  getHistory: async (pid) => {
    const {data} = await sb.from("entries").select("entry_date,data").eq("profile_id",pid).order("entry_date",{ascending:false}).limit(30);
    return (data||[]).map(r=>({...r.data, date:r.entry_date}));
  },
  // Habits
  getHabitData: async (pid) => {
    const {data} = await sb.from("habit_data").select("data").eq("profile_id",pid).single();
    return data?.data || {};
  },
  saveHabitData: async (pid, habitData) => {
    await sb.from("habit_data").upsert({profile_id:pid, data:habitData, updated_at:new Date().toISOString()},{onConflict:"profile_id"});
  },
  // Habit config
  getHabitConfig: async (pid) => {
    const {data} = await sb.from("habit_config").select("habits").eq("profile_id",pid).single();
    return data?.habits || null;
  },
  saveHabitConfig: async (pid, habits) => {
    await sb.from("habit_config").upsert({profile_id:pid, habits, updated_at:new Date().toISOString()},{onConflict:"profile_id"});
  },
  // Tag config
  getTagConfig: async (pid) => {
    const {data} = await sb.from("tag_config").select("config").eq("profile_id",pid).single();
    return data?.config || null;
  },
  saveTagConfig: async (pid, config) => {
    await sb.from("tag_config").upsert({profile_id:pid, config, updated_at:new Date().toISOString()},{onConflict:"profile_id"});
  },
};

// ── HOOKS ─────────────────────────────────────────────────────────────────────
function useHabits(pid, selectedDate=TODAY) {
  const [data,   setData]   = useState({});
  const [habits, setHabits] = useState(()=>defHabitsFor(pid));
  const [cfg,    setCfg]    = useState(DEF_CFG);
  const [loaded, setLoaded] = useState(false);

  useEffect(()=>{
    let live=true;
    (async()=>{
      const [hd, hc, tc] = await Promise.all([DB.getHabitData(pid), DB.getHabitConfig(pid), DB.getTagConfig(pid)]);
      if(!live) return;
      if(hd) setData(hd);
      if(hc) setHabits(hc);
      if(tc) setCfg(tc);
      setLoaded(true);
    })();
    return ()=>{live=false;};
  },[pid]);

  const toggle = async id => {
    const u = {...data,[selectedDate]:{...(data[selectedDate]||{}),[id]:!(data[selectedDate]?.[id])}};
    setData(u);
    await DB.saveHabitData(pid, u);
  };
  const saveHabits = async h => { setHabits(h); await DB.saveHabitConfig(pid, h); };
  const saveCfg    = async c => { setCfg(c);    await DB.saveTagConfig(pid, c); };

  const streak = id => {
    let s=0, d=new Date();
    for(let i=0;i<365;i++){const k=d.toISOString().split("T")[0];if(data[k]?.[id]){s++;d.setDate(d.getDate()-1);}else break;}
    return s;
  };
  const pct30 = id => {
    let n=0;
    for(let i=0;i<30;i++){const d=new Date();d.setDate(d.getDate()-i);if(data[d.toISOString().split("T")[0]]?.[id])n++;}
    return Math.round(n/30*100);
  };
  const doneToday  = habits.filter(h=>!!data[TODAY]?.[h.id]).length;
  const doneOnDate = habits.filter(h=>!!data[selectedDate]?.[h.id]).length;

  return {data,habits,cfg,toggle,saveHabits,saveCfg,streak,pct30,doneToday,doneOnDate,loaded};
}

function useEntry(pid, selectedDate=TODAY) {
  const blank = ()=>({date:selectedDate,energy:"",moods:[],influences:[],sleep:"",
    god:{scripture:"",stoodOut:"",showing:"",applies:"",prayer:""},
    thoughts:"",happened:"",wins:"",gratitude:["","",""],
    trading:{vix:"",bias:"",context:"",levels:"",aplus:"",avoid:"",live:"",followed:"",mistakes:"",wentWell:"",didntWork:"",adjust:"",screenshots:[]},
    fitness:{type:"",duration:"",notes:"",screenshots:[]},
    kidFitness:{workoutType:"",duration:"",notes:"",screenshots:[],runMiles:"",runMinutes:"",runSeconds:""},
    family:{moment:"",challenge:"",gratKids:""},
    school:{learned:"",hard:"",proud:""},mood:"",
  });
  const [entry,   setEntry]   = useState(blank);
  const [history, setHistory] = useState([]);
  const [status,  setStatus]  = useState("");
  const timerRef = useRef(null);
  const entryRef = useRef(entry);
  entryRef.current = entry;

  useEffect(()=>{
    let live=true;
    setEntry(blank());
    (async()=>{
      const [e, hist] = await Promise.all([DB.getEntry(pid, selectedDate), DB.getHistory(pid)]);
      if(!live) return;
      if(e) setEntry(e);
      setHistory(hist);
    })();
    return ()=>{live=false;};
  },[pid, selectedDate]);

  const persist = async data => { await DB.saveEntry(pid, selectedDate, data); };

  const upd = (path,val) => {
    setEntry(prev=>{
      const n={...prev};
      const parts=path.split(".");
      let obj=n;
      for(let i=0;i<parts.length-1;i++){obj[parts[i]]={...obj[parts[i]]};obj=obj[parts[i]];}
      obj[parts[parts.length-1]]=val;
      if(timerRef.current) clearTimeout(timerRef.current);
      setStatus("saving");
      timerRef.current=setTimeout(async()=>{
        await persist(n);
        setStatus("saved");
        setTimeout(()=>setStatus(""),2000);
      },1500);
      return n;
    });
  };
  const toggleArr=(path,v)=>{const cur=path.split(".").reduce((o,k)=>o?.[k],entryRef.current)||[];upd(path,cur.includes(v)?cur.filter(x=>x!==v):[...cur,v]);};
  const save = async()=>{ await persist(entryRef.current); };
  return {entry,upd,save,history,status,toggleArr};
}

function useSelectedDate() {
  const [date,setDate]=useState(TODAY);
  const isToday=date===TODAY;
  const prev=()=>{const d=new Date(date+"T12:00:00");d.setDate(d.getDate()-1);setDate(d.toISOString().split("T")[0]);};
  const next=()=>{if(isToday)return;const d=new Date(date+"T12:00:00");d.setDate(d.getDate()+1);setDate(d.toISOString().split("T")[0]);};
  const goToday=()=>setDate(TODAY);
  return {date,prev,next,goToday,isToday};
}

// ── PRIMITIVES ────────────────────────────────────────────────────────────────
const FI=({value,onChange,placeholder,type="text",style={}})=>(
  <input type={type} value={value||""} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
    style={{width:"100%",background:T.bg2,border:`1px solid ${T.border}`,borderRadius:10,color:T.w1,fontSize:15,padding:"11px 14px",outline:"none",...style}}/>
);
const FT=({value,onChange,placeholder,minH=80})=>(
  <textarea value={value||""} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
    style={{width:"100%",background:T.bg2,border:`1px solid ${T.border}`,borderRadius:10,color:T.w1,fontSize:15,padding:"11px 14px",outline:"none",minHeight:minH,lineHeight:1.6}}/>
);
const FL=({children,mt=16,mb=7})=>(
  <div style={{fontSize:11,fontWeight:600,color:T.w3,letterSpacing:"1px",textTransform:"uppercase",marginTop:mt,marginBottom:mb}}>{children}</div>
);
function Tags({opts,sel,onToggle,single}){
  return <div style={{display:"flex",flexWrap:"wrap",gap:7}}>
    {opts.map(o=>{const on=single?sel===o:(Array.isArray(sel)&&sel.includes(o));return(
      <button key={o} onClick={()=>onToggle(o)} style={{padding:"7px 14px",borderRadius:20,fontSize:13,cursor:"pointer",border:`1px solid ${on?T.w1:T.border}`,background:on?T.w1:T.w5,color:on?"#000":T.w3,fontWeight:on?600:400,transition:"all .15s"}}>{o}</button>
    );})}
  </div>;
}
function Card({title,icon,children,open:initOpen=false}){
  const [open,setOpen]=useState(initOpen);
  return(
    <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,marginBottom:10,overflow:"hidden"}}>
      <div onClick={()=>setOpen(p=>!p)} style={{display:"flex",alignItems:"center",padding:"14px 16px",cursor:"pointer",gap:10,userSelect:"none"}}>
        {icon&&<div style={{width:30,height:30,borderRadius:8,background:T.bg2,border:`1px solid ${T.border}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:15,flexShrink:0}}>{icon}</div>}
        <div style={{flex:1,fontSize:15,fontWeight:600,color:T.w1}}>{title}</div>
        <svg style={{transition:"transform .2s",transform:open?"rotate(180deg)":"none",color:T.w4,flexShrink:0}} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      {open&&<div style={{padding:"0 16px 16px",borderTop:`1px solid ${T.sep}`}}>{children}</div>}
    </div>
  );
}

// ── DATE NAV ──────────────────────────────────────────────────────────────────
function DateNav({date,prev,next,goToday,isToday}){
  return(
    <div style={{display:"flex",alignItems:"center",background:T.bg2,borderBottom:`1px solid ${T.sep}`,padding:"8px 14px",gap:6}}>
      <button onClick={prev} style={{width:34,height:34,borderRadius:"50%",border:`1px solid ${T.border}`,background:"none",color:T.w2,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:20}}>‹</button>
      <div style={{flex:1,textAlign:"center"}}>
        <div style={{fontSize:14,fontWeight:600,color:isToday?T.w1:T.w2}}>{isToday?"Today":fmtDate(date)}</div>
        {!isToday&&<div style={{fontSize:10,color:T.w4,marginTop:1}}>{date}</div>}
      </div>
      <button onClick={next} disabled={isToday} style={{width:34,height:34,borderRadius:"50%",border:`1px solid ${T.border}`,background:"none",color:isToday?"rgba(255,255,255,.1)":T.w2,cursor:isToday?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:20}}>›</button>
      {!isToday&&<button onClick={goToday} style={{padding:"5px 11px",borderRadius:12,border:`1px solid ${T.border}`,background:T.w5,color:T.w3,fontSize:11,cursor:"pointer",fontWeight:600,marginLeft:2,flexShrink:0}}>Today</button>}
    </div>
  );
}

// ── TOP BAR ───────────────────────────────────────────────────────────────────
function TopBar({profile,onBack,status,onSave,showSave}){
  const label=status==="saving"?"Saving…":status==="saved"?"✓ Saved":"Save";
  return(
    <div style={{padding:"12px 16px",background:T.bg2,borderBottom:`1px solid ${T.sep}`,display:"flex",alignItems:"center",gap:10,position:"sticky",top:0,zIndex:30}}>
      <button onClick={onBack} style={{background:"none",border:"none",color:T.w3,cursor:"pointer",display:"flex",alignItems:"center",gap:6,fontSize:14,fontWeight:500,padding:"4px 0",flexShrink:0}}>
        <svg width="10" height="17" viewBox="0 0 10 18" fill="none"><path d="M9 1L1 9L9 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        Family
      </button>
      <div style={{flex:1,textAlign:"center"}}>
        <div style={{fontSize:16,fontWeight:700,color:T.w1,display:"flex",alignItems:"center",justifyContent:"center",gap:7}}>
          <span style={{...GS,fontSize:17,lineHeight:1}}>{profile.emoji}</span>{profile.name}
        </div>
        <div style={{fontSize:10,color:T.w4,marginTop:1}}>{fmtDate(TODAY)}</div>
      </div>
      {showSave
        ?<button onClick={onSave} style={{background:status==="saved"?"rgba(255,255,255,.12)":"rgba(255,255,255,.08)",border:`1px solid ${status==="saved"?"rgba(255,255,255,.25)":T.border}`,color:status==="saved"?T.w1:T.w3,borderRadius:20,padding:"7px 16px",fontSize:13,fontWeight:600,cursor:"pointer",minWidth:70,transition:"all .2s"}}>{label}</button>
        :<div style={{width:70,textAlign:"right",fontSize:12,color:T.w4}}>{status==="saving"?"Saving…":status==="saved"?"✓":""}</div>
      }
    </div>
  );
}

// ── TAB STRIP ─────────────────────────────────────────────────────────────────
function TabStrip({tabs,active,onChange}){
  return(
    <div style={{display:"flex",overflowX:"auto",background:T.bg2,borderBottom:`1px solid ${T.sep}`,WebkitOverflowScrolling:"touch"}}>
      {tabs.map(t=>(
        <button key={t} onClick={()=>onChange(t)} style={{background:"none",border:"none",color:active===t?T.w1:T.w4,fontSize:13,fontWeight:active===t?700:400,padding:"11px 14px",cursor:"pointer",borderBottom:`2px solid ${active===t?"rgba(255,255,255,.6)":"transparent"}`,whiteSpace:"nowrap",flexShrink:0,transition:"all .15s"}}>{t}</button>
      ))}
    </div>
  );
}

// ── PASTE ZONE ────────────────────────────────────────────────────────────────
function PasteZone({images,onAdd,onRemove,label}){
  const [drag,setDrag]=useState(false);
  const fileRef=useRef();
  const processFile=f=>{
    if(!f||!f.type.startsWith("image/"))return;
    const r=new FileReader();
    r.onload=ev=>{const b64=ev.target.result.split(",")[1];onAdd({id:uid(),base64:b64,type:f.type,preview:ev.target.result});};
    r.readAsDataURL(f);
  };
  useEffect(()=>{
    const h=e=>{const items=e.clipboardData?.items||[];for(const item of items){if(item.type.startsWith("image/")){processFile(item.getAsFile());break;}}};
    document.addEventListener("paste",h);return()=>document.removeEventListener("paste",h);
  },[]);
  return(
    <div>
      {images.length>0&&<div style={{display:"flex",flexWrap:"wrap",gap:8,marginBottom:10}}>
        {images.map(img=>(
          <div key={img.id} style={{position:"relative"}}>
            <img src={img.preview} alt="" style={{width:100,height:100,objectFit:"cover",borderRadius:10,border:`1px solid ${T.border}`,display:"block"}}/>
            <button onClick={()=>onRemove(img.id)} style={{position:"absolute",top:4,right:4,width:20,height:20,borderRadius:"50%",background:"rgba(0,0,0,.8)",border:`1px solid ${T.border}`,color:T.w3,fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>✕</button>
          </div>
        ))}
      </div>}
      <input ref={fileRef} type="file" accept="image/*" multiple style={{display:"none"}} onChange={e=>{Array.from(e.target.files||[]).forEach(processFile);e.target.value="";}}/>
      <button onClick={()=>fileRef.current?.click()} onDragOver={e=>{e.preventDefault();setDrag(true);}} onDragLeave={()=>setDrag(false)} onDrop={e=>{e.preventDefault();setDrag(false);Array.from(e.dataTransfer.files||[]).forEach(processFile);}}
        style={{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:6,border:`1.5px dashed ${drag?"rgba(255,255,255,.4)":T.border}`,borderRadius:12,padding:"16px 14px",background:drag?T.w5:"rgba(255,255,255,.03)",cursor:"pointer",transition:"all .15s"}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={T.w3} strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
          <span style={{fontSize:14,fontWeight:600,color:T.w2}}>Add Photo</span>
        </div>
        <span style={{fontSize:11,color:T.w4}}>Tap to choose · or drag & drop · or paste</span>
      </button>
    </div>
  );
}

// ── HABIT LIST ────────────────────────────────────────────────────────────────
function HabitList({pid,selectedDate=TODAY}){
  const {data,habits,toggle,streak,doneOnDate}=useHabits(pid,selectedDate);
  const isToday=selectedDate===TODAY;
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:14,padding:"14px 16px",marginBottom:12}}>
        <div style={{fontSize:28,fontWeight:700,color:T.w1,lineHeight:1}}>{doneOnDate}<span style={{fontSize:16,color:T.w3,fontWeight:400}}>/{habits.length}</span></div>
        <div style={{fontSize:11,color:T.w3,marginTop:4,fontWeight:600,textTransform:"uppercase",letterSpacing:"1px"}}>{isToday?"Habits Complete Today":`Habits — ${fmtDate(selectedDate)}`}</div>
        <div style={{marginTop:10,height:3,background:"rgba(255,255,255,.07)",borderRadius:2,overflow:"hidden"}}>
          <div style={{width:habits.length>0?`${doneOnDate/habits.length*100}%`:"0%",height:"100%",background:"rgba(255,255,255,.5)",borderRadius:2,transition:"width .4s"}}/>
        </div>
      </div>
      {habits.map(h=>{const done=!!data[selectedDate]?.[h.id];const s=streak(h.id);return(
        <div key={h.id} onClick={()=>toggle(h.id)} style={{display:"flex",alignItems:"center",background:T.card,border:`1px solid ${done?"rgba(255,255,255,.2)":T.border}`,borderRadius:14,padding:"14px 16px",marginBottom:8,cursor:"pointer",transition:"all .15s",gap:12}}>
          <div style={{width:38,height:38,borderRadius:10,background:T.bg2,border:`1px solid ${T.border}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:19,flexShrink:0,...GS}}>{h.e}</div>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:600,color:done?T.w1:T.w2}}>{h.label}</div>
            {s>0&&<div style={{fontSize:11,color:T.w3,marginTop:2}}>🔥 {s} day streak</div>}
          </div>
          <div style={{width:26,height:26,borderRadius:"50%",border:`1.5px solid ${done?"rgba(255,255,255,.6)":"rgba(255,255,255,.15)"}`,background:done?"rgba(255,255,255,.12)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all .2s"}}>
            {done&&<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={T.w1} strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
          </div>
        </div>
      );})}
    </div>
  );
}

// ── MONTH CELL ────────────────────────────────────────────────────────────────
function MonthCell({day,done,isToday}){
  return <div style={{aspectRatio:"1",borderRadius:5,background:done?"rgba(255,255,255,.9)":isToday?"rgba(255,255,255,.12)":"rgba(255,255,255,.05)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,color:done?"#000":isToday?T.w1:T.w3,fontWeight:done||isToday?700:400,border:isToday&&!done?`1px solid rgba(255,255,255,.25)`:"none"}}>{day}</div>;
}

// ── REPORTS ───────────────────────────────────────────────────────────────────
function Reports({pid}){
  const {data,habits,streak,pct30}=useHabits(pid);
  const [view,setView]=useState("monthly");
  const now=new Date();
  const [year,setYear]=useState(now.getFullYear());
  const [month,setMonth]=useState(now.getMonth());
  const prevMonth=()=>{if(month===0){setMonth(11);setYear(y=>y-1);}else setMonth(m=>m-1);};
  const nextMonth=()=>{if(month===11){setMonth(0);setYear(y=>y+1);}else setMonth(m=>m+1);};
  const monthLabel=new Date(year,month,1).toLocaleDateString("en-US",{month:"long",year:"numeric"});
  const overall30=habits.length>0?Math.round(habits.reduce((s,h)=>s+pct30(h.id),0)/habits.length):0;
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:12}}>
        <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:12}}>30-Day Overview</div>
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8,textAlign:"center"}}>
          {[{n:`${overall30}%`,l:"Overall"},{n:Math.max(0,...habits.map(h=>streak(h.id))),l:"Best Streak 🔥"},{n:`${habits.filter(h=>!!data[TODAY]?.[h.id]).length}/${habits.length}`,l:"Today"}].map((s,i)=>(
            <div key={i}><div style={{fontSize:24,fontWeight:700,color:T.w1,lineHeight:1}}>{s.n}</div><div style={{fontSize:10,color:T.w3,marginTop:4,fontWeight:500}}>{s.l}</div></div>
          ))}
        </div>
      </div>
      <div style={{display:"flex",background:T.card,border:`1px solid ${T.border}`,borderRadius:10,padding:3,marginBottom:12,gap:2}}>
        {["monthly","yearly"].map(v=><button key={v} onClick={()=>setView(v)} style={{flex:1,padding:"8px",borderRadius:8,background:view===v?"rgba(255,255,255,.1)":"transparent",border:"none",color:view===v?T.w1:T.w3,fontSize:13,fontWeight:view===v?600:400,cursor:"pointer",textTransform:"capitalize"}}>{v}</button>)}
      </div>
      {view==="monthly"&&<div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12,background:T.card,border:`1px solid ${T.border}`,borderRadius:12,padding:"10px 14px"}}>
        <button onClick={prevMonth} style={{background:"none",border:"none",color:T.w2,cursor:"pointer",fontSize:20,padding:"2px 8px"}}>‹</button>
        <div style={{fontSize:14,fontWeight:600,color:T.w1}}>{monthLabel}</div>
        <button onClick={nextMonth} style={{background:"none",border:"none",color:T.w2,cursor:"pointer",fontSize:20,padding:"2px 8px"}}>›</button>
      </div>}
      {habits.map(h=>{
        const s=streak(h.id),p=pct30(h.id);
        const days=getDaysInMonth(year,month),firstDay=getFirstDayOfWeek(year,month);
        const cells=[...Array(firstDay).fill(null),...Array.from({length:days},(_,i)=>i+1)];
        return(
          <div key={h.id} style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:10}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4}}>
              <div style={{display:"flex",alignItems:"center",gap:10}}><span style={{fontSize:18,...GS}}>{h.e}</span><span style={{fontSize:15,fontWeight:600,color:T.w1}}>{h.label}</span></div>
              <div style={{display:"flex",gap:10,alignItems:"center"}}>{s>0&&<span style={{fontSize:12,color:T.w3}}>🔥 {s}d</span>}<span style={{fontSize:13,fontWeight:700,color:T.w1}}>{p}%</span></div>
            </div>
            <div style={{height:3,background:"rgba(255,255,255,.07)",borderRadius:2,marginBottom:10,overflow:"hidden"}}><div style={{width:`${p}%`,height:"100%",background:"rgba(255,255,255,.55)",borderRadius:2}}/></div>
            {view==="monthly"&&<>
              <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:2,marginBottom:3}}>{["S","M","T","W","T","F","S"].map((d,i)=><div key={i} style={{textAlign:"center",fontSize:9,color:T.w4,fontWeight:600}}>{d}</div>)}</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:2}}>{cells.map((day,i)=>{if(!day)return <div key={i}/>;const k=dKey(year,month,day);return <MonthCell key={i} day={day} done={!!data[k]?.[h.id]} isToday={k===TODAY}/>;})}</div>
            </>}
            {view==="yearly"&&(()=>{const dots=[];for(let m=0;m<12;m++){for(let d=1;d<=getDaysInMonth(year,m);d++){const k=dKey(year,m,d);dots.push(!!data[k]?.[h.id]);}}return <div style={{display:"flex",flexWrap:"wrap",gap:2,marginTop:4}}>{dots.map((done,i)=><div key={i} style={{width:7,height:7,borderRadius:1.5,background:done?"rgba(255,255,255,.9)":"rgba(255,255,255,.07)"}}/>)}</div>;})()}
          </div>
        );
      })}
    </div>
  );
}

// ── HISTORY VIEW ──────────────────────────────────────────────────────────────
function HistoryView({pid}){
  const {history}=useEntry(pid);
  if(!history.length)return <div style={{minHeight:"60vh",background:T.bg,display:"flex",alignItems:"center",justifyContent:"center",color:T.w4,textAlign:"center",fontSize:15,padding:40,lineHeight:1.8}}>No saved entries yet.<br/>Fill out today — it auto-saves.</div>;
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      {history.map((e,i)=>(
        <div key={i} style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"14px 16px",marginBottom:10}}>
          <div style={{fontSize:12,fontWeight:700,color:T.w3,textTransform:"uppercase",letterSpacing:"1px",marginBottom:8}}>{fmtDate(e.date)}</div>
          {(e.thoughts||e.wins)&&<div style={{fontSize:14,color:T.w2,lineHeight:1.5,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",marginBottom:8}}>{e.thoughts||e.wins}</div>}
          <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
            {e.moods?.map(m=><span key={m} style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:T.w5,color:T.w3,fontWeight:500}}>{m}</span>)}
            {e.mood&&<span style={{fontSize:15}}>{e.mood}</span>}
            {e.energy&&<span style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:"rgba(255,255,255,.1)",color:T.w1,fontWeight:600}}>{e.energy}</span>}
            {e.sleep&&<span style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:T.w5,color:T.w3}}>💤 {e.sleep}h</span>}
            {e.trading?.followed&&<span style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:T.w5,color:T.w3}}>System: {e.trading.followed}</span>}
            {e.fitness?.type&&<span style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:T.w5,color:T.w3}}>💪 {e.fitness.type}</span>}
            {e.god?.scripture&&<span style={{fontSize:11,padding:"3px 10px",borderRadius:20,background:T.w5,color:T.w3}}>✝️ {e.god.scripture}</span>}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── TRADING LOGS ──────────────────────────────────────────────────────────────
function TradingLogs(){
  const {history}=useEntry("dalton");
  const [expanded,setExpanded]=useState(null);
  const logs=history.filter(e=>e.trading&&(e.trading.vix||e.trading.bias||e.trading.live||e.trading.followed||e.trading.mistakes));
  if(!logs.length)return <div style={{minHeight:"60vh",background:T.bg,display:"flex",alignItems:"center",justifyContent:"center",color:T.w4,textAlign:"center",fontSize:15,padding:40,lineHeight:1.8}}>No trading logs yet.</div>;
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:14,padding:"14px 16px",marginBottom:14}}>
        <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:10}}>All Time</div>
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",textAlign:"center",gap:8}}>
          {[{n:logs.length,l:"Days Logged"},{n:logs.filter(e=>e.trading?.followed==="Yes").length,l:"System ✓"},{n:logs.filter(e=>e.trading?.followed==="No").length,l:"System ✗"}].map((s,i)=>(
            <div key={i}><div style={{fontSize:24,fontWeight:700,color:T.w1}}>{s.n}</div><div style={{fontSize:10,color:T.w3,marginTop:3,fontWeight:500}}>{s.l}</div></div>
          ))}
        </div>
      </div>
      {logs.map((e,i)=>{const t=e.trading,open=expanded===i;return(
        <div key={i} style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,marginBottom:10,overflow:"hidden"}}>
          <div onClick={()=>setExpanded(open?null:i)} style={{padding:"14px 16px",display:"flex",alignItems:"center",gap:10,cursor:"pointer",userSelect:"none"}}>
            <div style={{flex:1}}>
              <div style={{fontSize:13,fontWeight:700,color:T.w3,letterSpacing:".8px",textTransform:"uppercase",marginBottom:4}}>{fmtDate(e.date)}</div>
              <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
                {t.vix&&<span style={{fontSize:11,padding:"2px 8px",borderRadius:10,background:T.w5,color:T.w3}}>VIX {t.vix}</span>}
                {t.bias&&<span style={{fontSize:11,padding:"2px 8px",borderRadius:10,background:T.w5,color:T.w3}}>{t.bias}</span>}
                {t.followed&&<span style={{fontSize:11,padding:"2px 8px",borderRadius:10,background:"rgba(255,255,255,.08)",color:t.followed==="Yes"?"rgba(255,255,255,.9)":t.followed==="No"?"rgba(255,255,255,.4)":"rgba(255,255,255,.65)",fontWeight:600}}>System: {t.followed}</span>}
              </div>
            </div>
            <svg style={{transition:"transform .2s",transform:open?"rotate(180deg)":"none",color:T.w4,flexShrink:0}} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="6 9 12 15 18 9"/></svg>
          </div>
          {open&&<div style={{padding:"0 16px 16px",borderTop:`1px solid ${T.sep}`}}>
            {t.context&&<><FL mt={12}>Context</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.55}}>{t.context}</div></>}
            {t.levels&&<><FL>Key Levels</FL><div style={{fontSize:14,color:T.w2}}>{t.levels}</div></>}
            {t.aplus&&<><FL>A+ Setup</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.55}}>{t.aplus}</div></>}
            {t.live&&<><FL>Live Log</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.6,whiteSpace:"pre-wrap",background:T.bg2,borderRadius:10,padding:"10px 12px"}}>{t.live}</div></>}
            {t.mistakes&&<><FL>Mistakes</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.55}}>{t.mistakes}</div></>}
            {t.wentWell&&<><FL>What Went Well</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.55}}>{t.wentWell}</div></>}
            {t.adjust&&<><FL>Tomorrow</FL><div style={{fontSize:14,color:T.w2,lineHeight:1.55}}>{t.adjust}</div></>}
            {t.screenshots?.length>0&&<><FL>Charts</FL><div style={{display:"flex",flexWrap:"wrap",gap:8}}>{t.screenshots.map(img=><img key={img.id} src={img.preview} alt="" style={{width:140,height:100,objectFit:"cover",borderRadius:10,border:`1px solid ${T.border}`}}/>)}</div></>}
          </div>}
        </div>
      );})}
    </div>
  );
}

// ── RUN HISTORY ───────────────────────────────────────────────────────────────
function RunHistory({pid}){
  const {history}=useEntry(pid);
  const runs=history.filter(e=>e.kidFitness?.runMiles&&(e.kidFitness?.runMinutes||e.kidFitness?.runSeconds)).map(e=>{
    const mi=parseFloat(e.kidFitness.runMiles)||0,mins=parseInt(e.kidFitness.runMinutes)||0,secs=parseInt(e.kidFitness.runSeconds)||0;
    const totalSecs=mins*60+secs,paceSecsMile=mi>0?Math.round(totalSecs/mi):0;
    return {date:e.date,mi,mins,secs,totalSecs,pace:`${Math.floor(paceSecsMile/60)}:${String(paceSecsMile%60).padStart(2,"0")}`};
  }).sort((a,b)=>a.date.localeCompare(b.date));
  if(!runs.length)return <div style={{minHeight:"60vh",background:T.bg,display:"flex",alignItems:"center",justifyContent:"center",color:T.w4,textAlign:"center",fontSize:15,padding:40,lineHeight:1.8}}>No runs logged yet.<br/>Log a run in Today → Fitness.</div>;
  const totalMiles=runs.reduce((s,r)=>s+r.mi,0);
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:12}}>
        <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:12}}>All Time</div>
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",textAlign:"center",gap:8}}>
          {[{n:runs.length,l:"Runs"},{n:`${totalMiles.toFixed(1)}mi`,l:"Total Miles"},{n:runs[runs.length-1]?.pace||"—",l:"Last Pace /mi"}].map((s,i)=>(
            <div key={i}><div style={{fontSize:22,fontWeight:700,color:T.w1,lineHeight:1}}>{s.n}</div><div style={{fontSize:10,color:T.w3,marginTop:4,fontWeight:500}}>{s.l}</div></div>
          ))}
        </div>
      </div>
      {runs.length>1&&(()=>{const maxSecs=Math.max(...runs.map(r=>r.totalSecs));return(
        <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:12}}>
          <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:12}}>Pace Trend</div>
          <div style={{display:"flex",alignItems:"flex-end",gap:4,height:60}}>
            {runs.slice(-12).map((r,i)=>{const h=maxSecs>0?Math.round((r.totalSecs/maxSecs)*56):20;return(
              <div key={i} style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:3}}>
                <div style={{width:"100%",height:h,background:"rgba(255,255,255,.25)",borderRadius:"4px 4px 0 0",minHeight:6}}/>
                <div style={{fontSize:8,color:T.w4,whiteSpace:"nowrap"}}>{r.pace}</div>
              </div>
            );})}
          </div>
        </div>
      );})()}
      <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:10}}>Run Log</div>
      {[...runs].reverse().map((r,i)=>(
        <div key={i} style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:14,padding:"14px 16px",marginBottom:8,display:"flex",alignItems:"center",gap:12}}>
          <div style={{fontSize:22,...GS}}>🏃</div>
          <div style={{flex:1}}>
            <div style={{fontSize:13,fontWeight:700,color:T.w3,textTransform:"uppercase",letterSpacing:".8px",marginBottom:2}}>{fmtDate(r.date)}</div>
            <div style={{fontSize:15,fontWeight:600,color:T.w1}}>{r.mi} mile{r.mi!==1?"s":""}</div>
          </div>
          <div style={{textAlign:"right"}}>
            <div style={{fontSize:16,fontWeight:700,color:T.w1}}>{r.mins}:{String(r.secs).padStart(2,"0")}</div>
            <div style={{fontSize:10,color:T.w3,marginTop:2}}>{r.pace} /mi</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── SETTINGS ──────────────────────────────────────────────────────────────────
function SettingsPanel({pid}){
  const {habits,cfg,saveHabits,saveCfg}=useHabits(pid);
  const [section,setSection]=useState("habits");
  const [newEmoji,setNE]=useState("✅");const [newName,setNN]=useState("");
  const [field,setField]=useState("moodOpts");const [newTag,setNT]=useState("");
  const FIELDS={energyOpts:"Energy",moodOpts:"Mood",influenceOpts:"Influenced By"};
  const addHabit=()=>{if(!newName.trim())return;saveHabits([...habits,{id:uid(),label:newName.trim(),e:newEmoji}]);setNN("");setNE("✅");};
  const addTag=()=>{if(!newTag.trim())return;saveCfg({...cfg,[field]:[...cfg[field],newTag.trim()]});setNT("");};
  return(
    <div style={{padding:"14px 14px 100px",background:T.bg,minHeight:"60vh"}}>
      <div style={{display:"flex",background:T.card,border:`1px solid ${T.border}`,borderRadius:10,padding:3,marginBottom:14,gap:2}}>
        {[{id:"habits",l:"Habits"},{id:"tags",l:"Tags & Options"}].map(s=>(
          <button key={s.id} onClick={()=>setSection(s.id)} style={{flex:1,padding:"8px",borderRadius:8,background:section===s.id?"rgba(255,255,255,.1)":"transparent",border:"none",color:section===s.id?T.w1:T.w3,fontSize:13,fontWeight:section===s.id?600:400,cursor:"pointer"}}>{s.l}</button>
        ))}
      </div>
      {section==="habits"&&<>
        <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",marginBottom:10}}>Current Habits</div>
        {habits.map(h=>(
          <div key={h.id} style={{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",background:T.card,border:`1px solid ${T.border}`,borderRadius:12,marginBottom:8}}>
            <span style={{fontSize:20,...GS}}>{h.e}</span>
            <span style={{flex:1,fontSize:15,color:T.w1}}>{h.label}</span>
            <button onClick={()=>saveHabits(habits.filter(x=>x.id!==h.id))} style={{background:T.w5,border:`1px solid ${T.border}`,color:T.w3,borderRadius:8,padding:"5px 10px",fontSize:12,cursor:"pointer"}}>Remove</button>
          </div>
        ))}
        <div style={{fontSize:11,color:T.w3,fontWeight:600,letterSpacing:"1px",textTransform:"uppercase",margin:"18px 0 10px"}}>Add New Habit</div>
        <div style={{display:"flex",gap:8}}>
          <input value={newEmoji} onChange={e=>setNE(e.target.value)} style={{width:48,background:T.card,border:`1px solid ${T.border}`,borderRadius:10,color:T.w1,fontSize:20,padding:"10px 6px",outline:"none",textAlign:"center"}}/>
          <input value={newName} onChange={e=>setNN(e.target.value)} onKeyDown={e=>e.key==="Enter"&&addHabit()} placeholder="Habit name..." style={{flex:1,background:T.card,border:`1px solid ${T.border}`,borderRadius:10,color:T.w1,fontSize:15,padding:"10px 14px",outline:"none"}}/>
          <button onClick={addHabit} style={{background:"rgba(255,255,255,.1)",border:`1px solid ${T.border}`,color:T.w1,borderRadius:10,padding:"10px 16px",fontSize:14,fontWeight:600,cursor:"pointer"}}>Add</button>
        </div>
      </>}
      {section==="tags"&&<>
        <div style={{display:"flex",gap:6,flexWrap:"wrap",marginBottom:14}}>
          {Object.entries(FIELDS).map(([k,l])=>(
            <button key={k} onClick={()=>setField(k)} style={{padding:"7px 14px",borderRadius:20,fontSize:12,cursor:"pointer",border:`1px solid ${field===k?T.w1:T.border}`,background:field===k?"rgba(255,255,255,.1)":T.w5,color:field===k?T.w1:T.w3,fontWeight:field===k?600:400}}>{l}</button>
          ))}
        </div>
        <div style={{display:"flex",flexWrap:"wrap",gap:8,marginBottom:16}}>
          {cfg[field]?.map(v=>(
            <div key={v} style={{display:"flex",alignItems:"center",gap:6,padding:"6px 12px",background:T.card,border:`1px solid ${T.border}`,borderRadius:20}}>
              <span style={{fontSize:13,color:T.w1}}>{v}</span>
              <button onClick={()=>saveCfg({...cfg,[field]:cfg[field].filter(x=>x!==v)})} style={{background:"none",border:"none",color:T.w3,cursor:"pointer",fontSize:14}}>✕</button>
            </div>
          ))}
        </div>
        <div style={{display:"flex",gap:8}}>
          <input value={newTag} onChange={e=>setNT(e.target.value)} onKeyDown={e=>e.key==="Enter"&&addTag()} placeholder="Add new option..." style={{flex:1,background:T.card,border:`1px solid ${T.border}`,borderRadius:10,color:T.w1,fontSize:15,padding:"10px 14px",outline:"none"}}/>
          <button onClick={addTag} style={{background:"rgba(255,255,255,.1)",border:`1px solid ${T.border}`,color:T.w1,borderRadius:10,padding:"10px 16px",fontSize:14,fontWeight:600,cursor:"pointer"}}>Add</button>
        </div>
      </>}
    </div>
  );
}

// ── AI COACH ──────────────────────────────────────────────────────────────────
function AIChat({profile,systemPrompt}){
  const [msgs,setMsgs]=useState([{role:"assistant",content:`Hey ${profile.name}. Ready when you are.`}]);
  const [input,setInput]=useState("");const [loading,setLoad]=useState(false);const [img,setImg]=useState(null);
  const fileRef=useRef();const endRef=useRef();
  useEffect(()=>{endRef.current?.scrollIntoView({behavior:"smooth"});},[msgs]);
  const processFile=f=>{if(!f||!f.type.startsWith("image/"))return;const r=new FileReader();r.onload=ev=>{const b64=ev.target.result.split(",")[1];setImg({base64:b64,type:f.type,preview:ev.target.result});};r.readAsDataURL(f);};
  const send=async()=>{
    if((!input.trim()&&!img)||loading)return;
    const um={role:"user",content:input||"Analyze this.",image:img?.base64,imgType:img?.type,preview:img?.preview};
    const nm=[...msgs,um];setMsgs(nm);setInput("");setImg(null);setLoad(true);
    try{
      const api=nm.map(m=>({role:m.role,content:m.image?[{type:"image",source:{type:"base64",media_type:m.imgType,data:m.image}},{type:"text",text:m.content}]:m.content}));
      const res=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":window.ENV.ANTHROPIC_KEY||"","anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"},body:JSON.stringify({model:"claude-sonnet-4-20250514",max_tokens:1000,system:systemPrompt,messages:api})});
      const d=await res.json();
      setMsgs(p=>[...p,{role:"assistant",content:d.content?.map(c=>c.text||"").join("")||d.error?.message||"Error."}]);
    }catch{setMsgs(p=>[...p,{role:"assistant",content:"Connection error."}]);}
    setLoad(false);
  };
  return(
    <>
      <div style={{minHeight:"50vh",padding:"14px 14px 120px",background:T.bg}}>
        {msgs.map((m,i)=>(
          <div key={i} style={{marginBottom:12,maxWidth:"85%",marginLeft:m.role==="user"?"auto":0,animation:"fadeUp .2s ease"}}>
            {m.role==="assistant"&&<div style={{fontSize:10,fontWeight:700,color:T.w4,letterSpacing:"1.5px",textTransform:"uppercase",marginBottom:4}}>AI COACH</div>}
            <div style={{padding:"12px 14px",borderRadius:m.role==="user"?"16px 16px 4px 16px":"16px 16px 16px 4px",fontSize:15,lineHeight:1.65,whiteSpace:"pre-wrap",wordBreak:"break-word",background:m.role==="user"?"rgba(255,255,255,.1)":T.card,border:`1px solid ${T.border}`,color:m.role==="user"?T.w1:T.w2}}>
              {m.preview&&<img src={m.preview} alt="" style={{maxWidth:160,borderRadius:8,marginBottom:8,display:"block"}}/>}
              {m.content}
            </div>
          </div>
        ))}
        {loading&&<div style={{marginBottom:12}}><div style={{fontSize:10,fontWeight:700,color:T.w4,letterSpacing:"1.5px",textTransform:"uppercase",marginBottom:4}}>AI COACH</div><div style={{padding:"14px 16px",borderRadius:"16px 16px 16px 4px",background:T.card,border:`1px solid ${T.border}`,display:"inline-flex",gap:5,alignItems:"center"}}>{[0,1,2].map(i=><span key={i} style={{width:6,height:6,borderRadius:"50%",background:T.w3,display:"inline-block",animation:`dot 1.2s ${i*.2}s infinite ease-in-out`}}/>)}</div></div>}
        <div ref={endRef}/>
      </div>
      <div style={{position:"sticky",bottom:0,background:T.bg,borderTop:`1px solid ${T.sep}`,padding:"10px 14px 20px",display:"flex",gap:8,alignItems:"flex-end",zIndex:10}}>
        <input type="file" ref={fileRef} accept="image/*" style={{display:"none"}} onChange={e=>processFile(e.target.files?.[0])}/>
        {img&&<div style={{position:"absolute",bottom:78,left:14,background:T.card,border:`1px solid ${T.border}`,borderRadius:12,padding:8,zIndex:20}}><img src={img.preview} alt="" style={{width:80,height:80,objectFit:"cover",borderRadius:8,display:"block"}}/><button onClick={()=>setImg(null)} style={{width:"100%",background:T.w5,border:"none",color:T.w3,fontSize:11,padding:"4px 0",borderRadius:6,cursor:"pointer",marginTop:4}}>Remove</button></div>}
        <button onClick={()=>fileRef.current?.click()} style={{width:38,height:38,borderRadius:"50%",border:`1px solid ${T.border}`,background:T.card,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:T.w3}}>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
        </button>
        <textarea value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send();}}} placeholder="Message coach..." style={{flex:1,background:T.card,border:`1px solid ${T.border}`,borderRadius:18,color:T.w1,fontSize:15,padding:"9px 14px",outline:"none",lineHeight:1.4,maxHeight:80,overflowY:"auto"}} rows={1}/>
        <button onClick={send} disabled={loading||(!input.trim()&&!img)} style={{width:38,height:38,borderRadius:"50%",background:"rgba(255,255,255,.12)",border:`1px solid ${T.border}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:T.w1,flexShrink:0,opacity:loading||(!input.trim()&&!img)?.4:1}}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
        </button>
      </div>
    </>
  );
}

// ── DALTON APP ────────────────────────────────────────────────────────────────
function DaltonApp({onBack}){
  const P=PROFILES[0];
  const [tab,setTab]=useState("Today");
  const {date,prev,next,goToday,isToday}=useSelectedDate();
  const {entry,upd,save,status,toggleArr}=useEntry("dalton",date);
  const {habits,cfg}=useHabits("dalton",date);
  const showSave=tab==="Today"||tab==="Trading";
  const addImg=(sec,img)=>upd(`${sec}.screenshots`,[...(entry[sec]?.screenshots||[]),img]);
  const rmImg=(sec,id)=>upd(`${sec}.screenshots`,(entry[sec]?.screenshots||[]).filter(i=>i.id!==id));
  const sys=`You are Dalton Hensley's personal life coach. BDM at MagicSchool AI. BJJ multiple times/week. Christian—Watermark Church, Regen. Married Stefanie, 4 boys: Dash(9,homeschool),Jett(7),Rush(5),Cruz(1). Anna TX. LTP options trader, SPY/SPX/QQQ 0DTE, Tradezella. Finances tight. Pillars: GOD|FAMILY|HEALTH|WORK|FINANCIAL FREEDOM. TODAY: Energy:${entry.energy||"?"} Sleep:${entry.sleep||"?"}h Moods:${(entry.moods||[]).join(",")||"none"} Thoughts:${entry.thoughts?.slice(0,200)||"none"} GOD:${entry.god?.scripture||"none"} Trading followed:${entry.trading?.followed||"?"}. Be direct, push him, connect dots.`;
  const TABS=["Today","Habits","Reports","Trading","Logs","Coach","History","Settings"];
  return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column"}}>
      <TopBar profile={P} onBack={onBack} status={status} onSave={save} showSave={showSave}/>
      <TabStrip tabs={TABS} active={tab} onChange={setTab}/>
      {(tab==="Today"||tab==="Habits"||tab==="Trading")&&<DateNav date={date} prev={prev} next={next} goToday={goToday} isToday={isToday}/>}
      <div style={{flex:1,overflowY:"auto"}}>
        {tab==="Today"&&<div style={{padding:"14px 14px 80px"}}>
          <Card title="Daily Metrics" icon="📊" open>
            <FL>Energy</FL><Tags opts={cfg.energyOpts} sel={entry.energy} onToggle={v=>upd("energy",entry.energy===v?"":v)} single/>
            <FL>Mood</FL><Tags opts={cfg.moodOpts} sel={entry.moods||[]} onToggle={v=>toggleArr("moods",v)}/>
            <FL>Influenced By</FL><Tags opts={cfg.influenceOpts} sel={entry.influences||[]} onToggle={v=>toggleArr("influences",v)}/>
            <FL>Sleep (hours)</FL><FI value={entry.sleep} onChange={v=>upd("sleep",v)} placeholder="7" type="number" style={{width:100}}/>
          </Card>
          <Card title="GOD" icon="✝️">
            <FL mt={12}>Scripture</FL><FI value={entry.god?.scripture} onChange={v=>upd("god.scripture",v)} placeholder="e.g. Matthew 16:24–26"/>
            <FL>What stood out</FL><FT value={entry.god?.stoodOut} onChange={v=>upd("god.stoodOut",v)} placeholder="What struck you?"/>
            <FL>What God is showing me</FL><FT value={entry.god?.showing} onChange={v=>upd("god.showing",v)} placeholder="What is He revealing?"/>
            <FL>How this applies today</FL><FT value={entry.god?.applies} onChange={v=>upd("god.applies",v)} placeholder="Practical application..."/>
            <FL>Prayer</FL><FT value={entry.god?.prayer} onChange={v=>upd("god.prayer",v)} placeholder="Your prayer..."/>
          </Card>
          <Card title="Thoughts & Wins" icon="🧠">
            <FL mt={12}>Free Thoughts</FL><FT value={entry.thoughts} onChange={v=>upd("thoughts",v)} placeholder="Brain dump..." minH={100}/>
            <FL>What happened today?</FL><FT value={entry.happened} onChange={v=>upd("happened",v)} placeholder="Events, moments, decisions..."/>
            <FL>Wins</FL><FT value={entry.wins} onChange={v=>upd("wins",v)} placeholder="What did you win?"/>
            <FL>Gratitude</FL>
            {(entry.gratitude||["","",""]).map((g,i)=><FI key={i} value={g} onChange={v=>{const a=[...(entry.gratitude||["","",""])];a[i]=v;upd("gratitude",a);}} placeholder={`Grateful for #${i+1}...`} style={{marginBottom:8}}/>)}
          </Card>
          <Card title="Fitness" icon="💪">
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              <div><FL mt={12}>Type</FL><FI value={entry.fitness?.type} onChange={v=>upd("fitness.type",v)} placeholder="BJJ / Lift..."/></div>
              <div><FL mt={12}>Duration</FL><FI value={entry.fitness?.duration} onChange={v=>upd("fitness.duration",v)} placeholder="1h 15m"/></div>
            </div>
            <FL>Notes</FL><FT value={entry.fitness?.notes} onChange={v=>upd("fitness.notes",v)} placeholder="How was training?"/>
            <FL>Screenshots</FL><PasteZone images={entry.fitness?.screenshots||[]} onAdd={img=>addImg("fitness",img)} onRemove={id=>rmImg("fitness",id)} label="Add workout photo"/>
          </Card>
        </div>}
        {tab==="Trading"&&<div style={{padding:"14px 14px 80px"}}>
          <Card title="Pre-Market Plan" icon="📋" open>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              <div><FL mt={12}>VIX</FL><FI value={entry.trading?.vix} onChange={v=>upd("trading.vix",v)} placeholder="18.2"/></div>
              <div><FL mt={12}>Bias</FL><FI value={entry.trading?.bias} onChange={v=>upd("trading.bias",v)} placeholder="Bull/Bear/Neutral"/></div>
            </div>
            <FL>Context</FL><FI value={entry.trading?.context} onChange={v=>upd("trading.context",v)} placeholder="Market context..."/>
            <FL>Key Levels</FL><FI value={entry.trading?.levels} onChange={v=>upd("trading.levels",v)} placeholder="Support / resistance"/>
            <FL>A+ Setup Today</FL><FT value={entry.trading?.aplus} onChange={v=>upd("trading.aplus",v)} placeholder="What qualifies as A+ today?"/>
            <FL>What am I avoiding?</FL><FT value={entry.trading?.avoid} onChange={v=>upd("trading.avoid",v)} placeholder="FOMO traps..."/>
          </Card>
          <Card title="Live Trading Log" icon="📈">
            <FT value={entry.trading?.live} onChange={v=>upd("trading.live",v)} placeholder="Log trades as they happen..." minH={220}/>
            <FL>Chart Screenshots</FL><PasteZone images={entry.trading?.screenshots||[]} onAdd={img=>addImg("trading",img)} onRemove={id=>rmImg("trading",id)} label="Paste TradingView chart here"/>
          </Card>
          <Card title="Post-Market Debrief" icon="🧠">
            <FL mt={12}>Followed System?</FL><Tags opts={["Yes","No","Mixed"]} sel={entry.trading?.followed} onToggle={v=>upd("trading.followed",entry.trading?.followed===v?"":v)} single/>
            <FL>Mistakes</FL><FT value={entry.trading?.mistakes} onChange={v=>upd("trading.mistakes",v)} placeholder="What went wrong?"/>
            <FL>What went well</FL><FT value={entry.trading?.wentWell} onChange={v=>upd("trading.wentWell",v)} placeholder="Wins..."/>
            <FL>What didn't work</FL><FT value={entry.trading?.didntWork} onChange={v=>upd("trading.didntWork",v)} placeholder="What to fix..."/>
            <FL>Adjustment for tomorrow</FL><FT value={entry.trading?.adjust} onChange={v=>upd("trading.adjust",v)} placeholder="What changes tomorrow?"/>
          </Card>
        </div>}
        {tab==="Habits"  &&<HabitList pid="dalton" selectedDate={date}/>}
        {tab==="Reports" &&<Reports   pid="dalton"/>}
        {tab==="Logs"    &&<TradingLogs/>}
        {tab==="Coach"   &&<AIChat profile={P} systemPrompt={sys}/>}
        {tab==="History" &&<HistoryView pid="dalton"/>}
        {tab==="Settings"&&<SettingsPanel pid="dalton"/>}
      </div>
    </div>
  );
}

// ── STEFANIE APP ──────────────────────────────────────────────────────────────
function StefanieApp({onBack}){
  const P=PROFILES[1];
  const [tab,setTab]=useState("Today");
  const {date,prev,next,goToday,isToday}=useSelectedDate();
  const {entry,upd,save,status,toggleArr}=useEntry("stefanie",date);
  const {habits,cfg}=useHabits("stefanie",date);
  const sys=`You are Stefanie Hensley's personal coach. Wife to Dalton, Mom to Dash(9),Jett(7),Rush(5),Cruz(1). Anna TX. Christian. Manages household+homeschool. Dalton's anchor. Be warm, real, direct. TODAY: Energy:${entry.energy||"?"} Moods:${(entry.moods||[]).join(",")||"none"} Thoughts:${entry.thoughts?.slice(0,150)||"none"}`;
  const TABS=["Today","Habits","Reports","Coach","History","Settings"];
  return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column"}}>
      <TopBar profile={P} onBack={onBack} status={status} onSave={save} showSave={tab==="Today"}/>
      <TabStrip tabs={TABS} active={tab} onChange={setTab}/>
      {(tab==="Today"||tab==="Habits")&&<DateNav date={date} prev={prev} next={next} goToday={goToday} isToday={isToday}/>}
      <div style={{flex:1,overflowY:"auto"}}>
        {tab==="Today"&&<div style={{padding:"14px 14px 80px"}}>
          <Card title="Daily Metrics" icon="📊" open>
            <FL>Energy</FL><Tags opts={cfg.energyOpts} sel={entry.energy} onToggle={v=>upd("energy",entry.energy===v?"":v)} single/>
            <FL>Mood</FL><Tags opts={cfg.moodOpts} sel={entry.moods||[]} onToggle={v=>toggleArr("moods",v)}/>
            <FL>Sleep (hours)</FL><FI value={entry.sleep} onChange={v=>upd("sleep",v)} placeholder="7" type="number" style={{width:100}}/>
          </Card>
          <Card title="Faith" icon="✝️">
            <FL mt={12}>Scripture</FL><FI value={entry.god?.scripture} onChange={v=>upd("god.scripture",v)} placeholder="Today's scripture..."/>
            <FL>What stood out</FL><FT value={entry.god?.stoodOut} onChange={v=>upd("god.stoodOut",v)} placeholder="What struck you?"/>
            <FL>What God is showing me</FL><FT value={entry.god?.showing} onChange={v=>upd("god.showing",v)} placeholder="What is He revealing?"/>
            <FL>Prayer</FL><FT value={entry.god?.prayer} onChange={v=>upd("god.prayer",v)} placeholder="Your prayer..."/>
          </Card>
          <Card title="Family" icon="👨‍👩‍👧‍👦">
            <FL mt={12}>Best family moment today</FL><FT value={entry.family?.moment} onChange={v=>upd("family.moment",v)} placeholder="Something that made you smile..."/>
            <FL>One challenge</FL><FT value={entry.family?.challenge} onChange={v=>upd("family.challenge",v)} placeholder="Something hard today..."/>
            <FL>Grateful for the kids</FL><FT value={entry.family?.gratKids} onChange={v=>upd("family.gratKids",v)} placeholder="Something you're proud of..."/>
          </Card>
          <Card title="Thoughts & Wins" icon="🧠">
            <FL mt={12}>Free Thoughts</FL><FT value={entry.thoughts} onChange={v=>upd("thoughts",v)} placeholder="What's on your mind?" minH={100}/>
            <FL>Wins</FL><FT value={entry.wins} onChange={v=>upd("wins",v)} placeholder="What went well today?"/>
            <FL>Gratitude</FL>
            {(entry.gratitude||["","",""]).map((g,i)=><FI key={i} value={g} onChange={v=>{const a=[...(entry.gratitude||["","",""])];a[i]=v;upd("gratitude",a);}} placeholder={`Grateful for #${i+1}...`} style={{marginBottom:8}}/>)}
          </Card>
        </div>}
        {tab==="Habits"  &&<HabitList  pid="stefanie" selectedDate={date}/>}
        {tab==="Reports" &&<Reports    pid="stefanie"/>}
        {tab==="Coach"   &&<AIChat profile={P} systemPrompt={sys}/>}
        {tab==="History" &&<HistoryView pid="stefanie"/>}
        {tab==="Settings"&&<SettingsPanel pid="stefanie"/>}
      </div>
    </div>
  );
}

// ── KID APP ───────────────────────────────────────────────────────────────────
function KidApp({profile,onBack}){
  const [tab,setTab]=useState("Today");
  const {date,prev,next,goToday,isToday}=useSelectedDate();
  const {entry,upd,save,status}=useEntry(profile.id,date);
  const addImg=img=>upd("kidFitness.screenshots",[...(entry.kidFitness?.screenshots||[]),img]);
  const rmImg=id=>upd("kidFitness.screenshots",(entry.kidFitness?.screenshots||[]).filter(i=>i.id!==id));
  const isRun=entry.kidFitness?.workoutType==="Run";
  const TABS=["Today","Habits","Reports","Runs","History"];
  return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column"}}>
      <TopBar profile={profile} onBack={onBack} status={status} onSave={save} showSave={tab==="Today"}/>
      <TabStrip tabs={TABS} active={tab} onChange={setTab}/>
      {(tab==="Today"||tab==="Habits")&&<DateNav date={date} prev={prev} next={next} goToday={goToday} isToday={isToday}/>}
      <div style={{flex:1,overflowY:"auto"}}>
        {tab==="Today"&&<div style={{padding:"14px 14px 80px"}}>
          <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:10}}>
            <div style={{fontSize:13,fontWeight:600,color:T.w3,marginBottom:12,textTransform:"uppercase",letterSpacing:"1px"}}>How are you feeling?</div>
            <div style={{display:"flex",gap:6,justifyContent:"space-between"}}>
              {KID_MOODS.map(m=>{const emoji=m.split(" ")[0];return(
                <div key={m} onClick={()=>upd("mood",m)} style={{flex:1,borderRadius:12,background:entry.mood===m?"rgba(255,255,255,.1)":"rgba(255,255,255,.04)",border:`1.5px solid ${entry.mood===m?"rgba(255,255,255,.5)":"rgba(255,255,255,.06)"}`,display:"flex",flexDirection:"column",alignItems:"center",padding:"10px 4px",cursor:"pointer",transition:"all .15s"}}>
                  <span style={{fontSize:26}}>{emoji}</span>
                  <span style={{fontSize:9,color:entry.mood===m?T.w1:T.w4,marginTop:4,fontWeight:600,textTransform:"uppercase",letterSpacing:".4px"}}>{m.split(" ").slice(1).join(" ")}</span>
                </div>
              );})}
            </div>
          </div>
          <Card title="God Time" icon="✝️">
            <FL mt={12}>What did you read?</FL><FI value={entry.god?.scripture} onChange={v=>upd("god.scripture",v)} placeholder="e.g. John 3:16"/>
            <FL>What did God show you?</FL><FT value={entry.god?.showing} onChange={v=>upd("god.showing",v)} placeholder="Something you learned or felt..."/>
          </Card>
          <Card title="School" icon="🎒">
            <FL mt={12}>What did I learn today?</FL><FT value={entry.school?.learned} onChange={v=>upd("school.learned",v)} placeholder="The coolest thing I learned..."/>
            <FL>What was hard?</FL><FT value={entry.school?.hard} onChange={v=>upd("school.hard",v)} placeholder="Something I struggled with..."/>
            <FL>What am I proud of?</FL><FT value={entry.school?.proud} onChange={v=>upd("school.proud",v)} placeholder="Something I did great..."/>
          </Card>
          <Card title="Wins" icon="🏆">
            <FT value={entry.wins} onChange={v=>upd("wins",v)} placeholder="What went great today?" minH={80}/>
          </Card>
          <Card title="Gratitude" icon="🙏">
            <FL mt={12}>I'm grateful for...</FL>
            {(entry.gratitude||["","",""]).map((g,i)=><FI key={i} value={g} onChange={v=>{const a=[...(entry.gratitude||["","",""])];a[i]=v;upd("gratitude",a);}} placeholder={["Something good that happened today...","Someone I'm thankful for...","Something about my family..."][i]} style={{marginBottom:8}}/>)}
          </Card>
          <Card title="Fitness" icon="🏋️">
            <FL mt={12}>Workout Type</FL>
            <div style={{display:"flex",flexWrap:"wrap",gap:7,marginBottom:4}}>
              {WORKOUT_TYPES.map(t=>{const on=entry.kidFitness?.workoutType===t;return <button key={t} onClick={()=>upd("kidFitness.workoutType",on?"":t)} style={{padding:"7px 14px",borderRadius:20,fontSize:13,cursor:"pointer",border:`1px solid ${on?T.w1:T.border}`,background:on?T.w1:T.w5,color:on?"#000":T.w3,fontWeight:on?600:400,transition:"all .15s"}}>{t}</button>;})}
            </div>
            {isRun&&<><FL>Distance (miles)</FL><FI value={entry.kidFitness?.runMiles} onChange={v=>upd("kidFitness.runMiles",v)} placeholder="e.g. 1.5" type="number" style={{width:110}}/><FL>Time</FL><div style={{display:"flex",alignItems:"center",gap:8}}><FI value={entry.kidFitness?.runMinutes} onChange={v=>upd("kidFitness.runMinutes",v)} placeholder="Min" type="number" style={{width:80}}/><span style={{color:T.w3,fontSize:16,fontWeight:600}}>:</span><FI value={entry.kidFitness?.runSeconds} onChange={v=>upd("kidFitness.runSeconds",v)} placeholder="Sec" type="number" style={{width:80}}/><span style={{color:T.w4,fontSize:12}}>mm:ss</span></div></>}
            {!isRun&&entry.kidFitness?.workoutType&&<><FL>Duration</FL><FI value={entry.kidFitness?.duration} onChange={v=>upd("kidFitness.duration",v)} placeholder="e.g. 45 min"/></>}
            <FL>Notes</FL><FT value={entry.kidFitness?.notes} onChange={v=>upd("kidFitness.notes",v)} placeholder="How did it go?"/>
            <FL>Photos</FL><PasteZone images={entry.kidFitness?.screenshots||[]} onAdd={addImg} onRemove={rmImg} label="Add workout photo"/>
          </Card>
        </div>}
        {tab==="Habits"  &&<HabitList  pid={profile.id} selectedDate={date}/>}
        {tab==="Reports" &&<Reports    pid={profile.id}/>}
        {tab==="Runs"    &&<RunHistory pid={profile.id}/>}
        {tab==="History" &&<HistoryView pid={profile.id}/>}
      </div>
    </div>
  );
}

// ── RUSH (tiny) ───────────────────────────────────────────────────────────────
function TinyApp({profile,onBack}){
  const {entry,upd,save,status}=useEntry(profile.id);
  const {habits,data,toggle,streak}=useHabits(profile.id);
  const done=habits.filter(h=>!!data[TODAY]?.[h.id]).length;
  const allDone=done===habits.length&&habits.length>0;
  return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column"}}>
      <div style={{padding:"12px 16px",background:T.bg2,borderBottom:`1px solid ${T.sep}`,display:"flex",alignItems:"center",justifyContent:"space-between",position:"sticky",top:0,zIndex:30}}>
        <button onClick={onBack} style={{background:"none",border:"none",color:T.w3,cursor:"pointer",display:"flex",alignItems:"center",gap:6,fontSize:14,fontWeight:500}}>
          <svg width="10" height="17" viewBox="0 0 10 18" fill="none"><path d="M9 1L1 9L9 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>Family
        </button>
        <div style={{fontSize:17,fontWeight:700,color:T.w1,display:"flex",alignItems:"center",gap:6}}><span style={GS}>{profile.emoji}</span>{profile.name}</div>
        <div style={{fontSize:12,color:T.w4,minWidth:60,textAlign:"right"}}>{status==="saving"?"Saving…":status==="saved"?"✓":""}</div>
      </div>
      <div style={{flex:1,overflowY:"auto",padding:"16px 14px 60px"}}>
        <div style={{textAlign:"center",padding:"16px 0 20px"}}>
          <div style={{fontSize:50,...GS}}>🦁</div>
          <div style={{fontSize:28,fontWeight:800,color:T.w1,marginTop:6}}>Hey Rush!</div>
          <div style={{fontSize:14,color:T.w3,marginTop:4}}>Let's check in today 🙌</div>
        </div>
        <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:12}}>
          <div style={{fontSize:14,fontWeight:600,color:T.w1,textAlign:"center",marginBottom:14}}>How do you feel?</div>
          <div style={{display:"flex",gap:8,justifyContent:"center",flexWrap:"wrap"}}>
            {KID_MOODS.map(m=>{const emoji=m.split(" ")[0];return(
              <div key={m} onClick={()=>upd("mood",m)} style={{width:58,height:58,borderRadius:14,background:entry.mood===m?"rgba(255,255,255,.12)":"rgba(255,255,255,.04)",border:`2px solid ${entry.mood===m?"rgba(255,255,255,.5)":"rgba(255,255,255,.06)"}`,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"all .2s",transform:entry.mood===m?"scale(1.1)":"none",userSelect:"none"}}>
                <span style={{fontSize:32}}>{emoji}</span>
              </div>
            );})}
          </div>
        </div>
        <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:16,padding:"16px",marginBottom:12}}>
          <div style={{fontSize:14,fontWeight:600,color:T.w1,marginBottom:12,textAlign:"center"}}>Did you do these today?</div>
          {habits.map(h=>{const d=!!data[TODAY]?.[h.id];const s=streak(h.id);return(
            <div key={h.id} onClick={()=>toggle(h.id)} style={{display:"flex",alignItems:"center",borderRadius:14,padding:"16px 14px",marginBottom:8,cursor:"pointer",background:d?"rgba(255,255,255,.06)":"rgba(255,255,255,.02)",border:`1.5px solid ${d?"rgba(255,255,255,.2)":"rgba(255,255,255,.06)"}`,transition:"all .2s",gap:14,userSelect:"none"}}>
              <span style={{fontSize:36,...GS,flexShrink:0}}>{h.e}</span>
              <div style={{flex:1}}><div style={{fontSize:18,fontWeight:700,color:T.w1}}>{h.label}</div>{s>0&&<div style={{fontSize:12,color:T.w3,marginTop:2}}>🔥 {s} days!</div>}</div>
              <div style={{width:40,height:40,borderRadius:"50%",border:`2px solid ${d?"rgba(255,255,255,.5)":"rgba(255,255,255,.1)"}`,background:d?"rgba(255,255,255,.12)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",transition:"all .2s"}}>
                {d&&<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={T.w1} strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
              </div>
            </div>
          );})}
        </div>
        {allDone&&<div style={{textAlign:"center",padding:"20px",background:T.card,border:`1px solid ${T.border}`,borderRadius:16,animation:"pop .4s ease"}}>
          <div style={{fontSize:40}}>🎉🌟⭐️</div>
          <div style={{fontSize:22,fontWeight:800,color:T.w1,marginTop:8}}>Amazing Rush!</div>
          <div style={{fontSize:14,color:T.w3,marginTop:4}}>You did everything today!</div>
        </div>}
      </div>
    </div>
  );
}

// ── HOME SCREEN ───────────────────────────────────────────────────────────────
const HEADER_EMOJIS=["⚡","✝️","🥋","📖","💪","🛌","💧","📈","🏋️","🙏","⏰","💊"];
const PILLARS=[{e:"✝️",l:"Faith"},{e:"👨‍👩‍👧‍👦",l:"Family"},{e:"💪",l:"Health"},{e:"📈",l:"Work"},{e:"💰",l:"Freedom"}];

function ProfileCard({profile,onSelect}){
  const {habits,data,doneToday,loaded}=useHabits(profile.id);
  const isBaby=profile.role==="baby";
  const pct=habits.length>0?doneToday/habits.length:0;
  return(
    <div onClick={()=>!isBaby&&onSelect(profile)} style={{borderRadius:18,padding:"18px 16px",cursor:isBaby?"default":"pointer",background:T.card,border:`1px solid ${T.border}`,transition:"background .15s",opacity:isBaby?.45:1,position:"relative",overflow:"hidden",WebkitTapHighlightColor:"transparent"}}>
      <div style={{position:"absolute",bottom:-8,right:-6,fontSize:52,opacity:.07,...GS,userSelect:"none",pointerEvents:"none",lineHeight:1}}>{profile.emoji}</div>
      <div style={{fontSize:36,marginBottom:10,...GS}}>{profile.emoji}</div>
      <div style={{fontSize:19,fontWeight:700,color:T.w1,letterSpacing:"-.3px"}}>{profile.name}</div>
      <div style={{fontSize:11,color:T.w4,marginTop:2,fontWeight:500}}>{profile.sub}</div>
      {!isBaby&&habits.length>0&&<>
        <div style={{marginTop:12,height:2,background:"rgba(255,255,255,.07)",borderRadius:2,overflow:"hidden"}}><div style={{width:`${pct*100}%`,height:"100%",background:"rgba(255,255,255,.4)",borderRadius:2,transition:"width .4s"}}/></div>
        <div style={{fontSize:10,color:T.w4,fontWeight:600,marginTop:5}}>{loaded?`${doneToday}/${habits.length} today`:"Loading..."}</div>
      </>}
      {isBaby&&<div style={{fontSize:11,color:T.w4,marginTop:8}}>Coming soon 🍼</div>}
    </div>
  );
}

function HomeScreen({onSelect}){
  return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100vh",background:T.bg}}>
      <div style={{padding:"28px 18px 20px",borderBottom:`1px solid ${T.sep}`,position:"relative",overflow:"hidden"}}>
        <div style={{position:"absolute",inset:0,pointerEvents:"none",userSelect:"none",overflow:"hidden"}}>
          {HEADER_EMOJIS.map((e,i)=><span key={i} style={{position:"absolute",fontSize:22,...GS,opacity:.12,top:`${[12,55,30,70,20,80,45,10,65,35,50,75][i]}%`,left:`${[8,15,35,5,60,25,80,90,70,50,42,88][i]}%`,transform:`rotate(${[-15,20,-8,30,-20,10,-5,25,0,-12,18,-25][i]}deg)`}}>{e}</span>)}
        </div>
        <div style={{position:"relative"}}>
          <div style={{fontSize:11,color:T.w4,letterSpacing:"2.5px",textTransform:"uppercase",fontWeight:600,marginBottom:6}}>Hensley Family</div>
          <div style={{fontSize:30,fontWeight:800,color:T.w1,letterSpacing:"-.8px",lineHeight:1}}>Life OS</div>
          <div style={{fontSize:12,color:T.w4,marginTop:6,fontStyle:"italic",opacity:.7}}>"As iron sharpens iron, so one person sharpens another." — Prov. 27:17</div>
          <div style={{display:"flex",gap:6,marginTop:16,flexWrap:"wrap"}}>
            {PILLARS.map(({e,l})=><div key={l} style={{display:"flex",alignItems:"center",gap:5,padding:"5px 10px",background:"rgba(255,255,255,.05)",border:`1px solid ${T.border}`,borderRadius:20}}><span style={{fontSize:13,...GS}}>{e}</span><span style={{fontSize:11,color:T.w3,fontWeight:600}}>{l}</span></div>)}
          </div>
        </div>
      </div>
      <div style={{padding:"14px 14px 80px"}}>
        <div style={{background:"rgba(255,255,255,.04)",border:`1px solid ${T.border}`,borderRadius:12,padding:"10px 14px",display:"flex",gap:10,alignItems:"center",marginBottom:16}}>
          <span style={{fontSize:16,...GS}}>📱</span>
          <span style={{fontSize:12,color:T.w3}}>Safari: Share → <strong style={{color:T.w2}}>Add to Home Screen</strong> for app access</span>
        </div>
        <div style={{fontSize:11,color:T.w4,fontWeight:600,letterSpacing:"1.2px",textTransform:"uppercase",marginBottom:12}}>Who's checking in?</div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
          {PROFILES.map(p=><ProfileCard key={p.id} profile={p} onSelect={onSelect}/>)}
        </div>
      </div>
    </div>
  );
}

// ── ROOT ──────────────────────────────────────────────────────────────────────
function App(){
  const [profile,setProfile]=useState(null);
  return(
    <>
      {!profile                 &&<HomeScreen  onSelect={setProfile}/>}
      {profile?.role==="dalton" &&<DaltonApp   onBack={()=>setProfile(null)}/>}
      {profile?.role==="adult"  &&<StefanieApp onBack={()=>setProfile(null)}/>}
      {profile?.role==="kid"    &&<KidApp      profile={profile} onBack={()=>setProfile(null)}/>}
      {profile?.role==="tiny"   &&<TinyApp     profile={profile} onBack={()=>setProfile(null)}/>}
    </>
  );
}

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