/* ============================================================================
   MOWDEW HOMEOWNER — Pool chemistry timeline + Reschedule / message owner
   POV: Emma Walsh, 88 Crestline Ave (pool). Readings captured from a photo of
   the test strip on each verified visit, trended over time.
   ========================================================================= */

/* Homeowner POV: Emma Walsh, 88 Crestline Ave. Full readings live in
   POOL_CHEM_LOG (mowdew-chem.jsx, loaded first). CHEM_LOG kept as an alias. */
const CHEM_LOG = (window.POOL_CHEM_LOG || []);

/* ============================== POOL CHEMISTRY ====================== */
function HomeChemistry({ go, openFab }) {
  const log = window.POOL_CHEM_LOG || [];
  const latest = log[0];
  const [trendKey, setTrendKey] = React.useState('ph');
  const [showAll, setShowAll] = React.useState(false);
  const TREND_KEYS = ['ph', 'cl', 'alk'];
  const r = READINGS[trendKey];
  const series = log.map(x => x[trendKey]).reverse();
  const labels = log.map(x => x.short).reverse().map((s, i, a) => (i === 0 || i === a.length - 1 || i === Math.floor(a.length / 2)) ? s : '');
  labels[labels.length - 1] = 'Now';
  const inRange = log.filter(x => chemState(trendKey, x[trendKey]) === 'ideal').length;
  const span = r.max - r.min;

  return (
    <Screen padBottom={26} footer={<TabBar role="homeowner" active="h_chem" go={go} onFab={openFab} />}>
      <div style={{ padding: '8px 18px 6px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--aqua-500)', display: 'grid', placeItems: 'center', color: '#fff' }}><Icon name="droplet" size={21} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-500)', fontWeight: 600 }}>88 Crestline Ave</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-0.02em' }}>Your pool</div>
        </div>
        <Dewy size={42} mood="happy" />
      </div>

      {/* THE STAR — plain, reassuring verdict */}
      <div style={{ padding: '6px 18px 0' }}>
        <ChemVerdictHero reading={latest} size="lg" />
      </div>

      {/* what's in the water — the actual readings, simply framed */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="aqua" icon="flask" style={{ marginBottom: 10 }} meta={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--green-700)', fontWeight: 700 }}><Icon name="camera" size={13} />from today's visit</span>}>What's in the water</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          <ChemRow rkey="ph" value={latest.ph} />
          <div style={{ borderTop: '1px solid var(--ink-100)' }} />
          <ChemRow rkey="cl" value={latest.cl} note={latest.handled === 'cl' ? 'Diego topped it up' : null} />
          <div style={{ borderTop: '1px solid var(--ink-100)' }} />
          <ChemRow rkey="alk" value={latest.alk} />
        </div>
      </div>

      {/* per-reading trends — tap a reading, ~8 visits, ideal band shaded */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="trend-up" style={{ marginBottom: 12 }}>Trends over time</SectionHead>
        <div className="card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', gap: 7, marginBottom: 14 }}>
            {TREND_KEYS.map(k => {
              const on = trendKey === k;
              return (
                <button key={k} onClick={() => setTrendKey(k)} style={{ flex: 1, padding: '9px 6px', borderRadius: 11, border: on ? '1.5px solid var(--aqua-300,#7FD3DF)' : '1.5px solid var(--ink-100)', background: on ? 'var(--aqua-50)' : '#fff', cursor: 'pointer', textAlign: 'center' }}>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.06em', color: on ? 'var(--aqua-700)' : 'var(--ink-500)' }}>{READINGS[k].abbr}</div>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17, color: on ? 'var(--ink-900)' : 'var(--ink-500)', letterSpacing: '-0.02em' }}>{log[0][k].toFixed(READINGS[k].dp)}</div>
                </button>
              );
            })}
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontWeight: 700, fontSize: 13.5 }}>{r.label}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 700, color: 'var(--green-700)' }}><Icon name="check-circle" size={14} />{inRange} of {log.length} in range</span>
          </div>
          <ChemTrend points={series} labels={labels} ideal={[r.lo, r.hi]} rangeMin={r.min} rangeMax={r.max} color="var(--aqua-500)" />
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 10, fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-500)' }}>
            <span style={{ width: 14, height: 8, borderRadius: 3, background: 'var(--green-500)', opacity: .18, border: '1px solid var(--green-300)' }} />IDEAL {r.band}
          </div>
        </div>
      </div>

      {/* reading history */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="aqua" icon="ledger" style={{ marginBottom: 12 }} meta={<button onClick={() => setShowAll(s => !s)} style={{ border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 600, letterSpacing: '.06em', color: 'var(--aqua-700)' }}>{showAll ? 'SHOW LESS' : 'SHOW ALL'}</button>}>Every reading, on the record</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          {(showAll ? log : log.slice(0, 4)).map((x, i) => {
            const st = chemState('ph', x.ph);
            return (
              <div key={x.id} onClick={() => go('h_visit', { id: x.visit })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderTop: i ? '1px solid var(--ink-100)' : 'none', cursor: 'pointer' }}>
                <PhBadge value={x.ph} size={42} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13.5 }}>{x.date}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-500)', fontFamily: 'var(--font-mono)' }}>FC {x.cl.toFixed(1)} · TA {x.alk}{x.handled ? ' · handled on-site' : ''}</div>
                </div>
                {x.handled
                  ? <Chip tone="done" icon="check">Looked after</Chip>
                  : <div style={{ textAlign: 'right' }}>
                      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17, color: st === 'ideal' ? 'var(--green-700)' : st === 'low' ? 'var(--yellow-700)' : 'var(--chem-violet)' }}>{x.ph.toFixed(1)}</div>
                      <div style={{ fontSize: 10, color: 'var(--ink-400,#A8A498)', fontFamily: 'var(--font-mono)' }}>pH</div>
                    </div>}
                <Icon name="chevron-right" size={17} style={{ color: 'var(--ink-300)' }} />
              </div>
            );
          })}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '11px 13px', background: 'var(--aqua-50)', borderRadius: 12 }}>
          <Icon name="shield" size={16} style={{ color: 'var(--aqua-700)', flexShrink: 0 }} />
          <span style={{ fontSize: 12, color: 'var(--ink-700)', lineHeight: 1.45 }}>Every reading comes from a verified on-site visit — your pro tests, Mowdew records, you see it here.</span>
        </div>
      </div>
      {/* your equipment — every part on the record */}
      <div style={{ padding: '16px 18px 0' }}>
        <div onClick={() => go('h_equipment')} className="card" style={{ cursor: 'pointer', padding: 14, display: 'flex', alignItems: 'center', gap: 12, borderColor: 'var(--aqua-100)' }}>
          <span style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><EquipPaper type="pump" size={32} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Your equipment</div>
            <div style={{ fontSize: 12, color: 'var(--ink-500)' }}>5 parts · pump, filter, heater & more</div>
          </div>
          <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)' }} />
        </div>
      </div>
    </Screen>
  );
}

/* ============================== RESCHEDULE / MESSAGE OWNER ==========
   Upgraded: quick slots + a real date & time picker, reason chips, and a
   hand-off into the live negotiation thread (h_resched).                  */
function HomeRequest({ go, toast }) {
  const [mode, setMode] = React.useState('reschedule');
  const slots = ['Keep Mon, May 18', 'Thu, May 21', 'Fri, May 22', 'Skip this week'];
  const [slot, setSlot] = React.useState('Thu, May 21');
  const [custom, setCustom] = React.useState(false);
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const REASONS = ['Guests coming', 'Gate will be locked', "We'll be away", 'Rain makeup'];
  const [msg, setMsg] = React.useState('We have a pool party Wednesday — could Diego come Thursday instead?');
  const to = custom ? (date && time ? `${date} · ${time}` : null) : slot;
  const ready = mode === 'message' ? msg.trim().length > 0 : !!to;
  const send = () => {
    if (mode === 'message') { toast('Message sent to Diego', 'green'); go('h_feed'); return; }
    toast('Request sent to Diego', 'green');
    go('h_resched', { fresh: true, to, note: msg.trim() });
  };
  return (
    <Screen padBottom={24} footer={
      <ActionBar>
        <button onClick={send} disabled={!ready} className="btn btn-primary btn-lg btn-block"><Icon name="send" size={19} />{mode === 'reschedule' ? 'Send reschedule request' : 'Send message'}</button>
      </ActionBar>}>
      <TopBar title="Reschedule or message" subtitle="Goes to Diego — your pool pro" onBack={() => go('h_feed')} />

      {/* mode switch */}
      <div style={{ padding: '4px 18px 0' }}>
        <div style={{ display: 'flex', gap: 7, background: 'var(--ink-50)', padding: 5, borderRadius: 14, border: '1px solid var(--ink-100)' }}>
          {[['reschedule', 'Reschedule', 'calendar-check'], ['message', 'Message', 'message']].map(([id, lb, ic]) => (
            <button key={id} onClick={() => setMode(id)} style={{ flex: 1, padding: '11px 6px', borderRadius: 10, border: 'none', cursor: 'pointer', fontSize: 13.5, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7, background: mode === id ? '#fff' : 'transparent', color: mode === id ? 'var(--ink-900)' : 'var(--ink-500)', boxShadow: mode === id ? 'var(--shadow-sm)' : 'none' }}><Icon name={ic} size={16} />{lb}</button>
          ))}
        </div>
      </div>

      {/* provider context — which provider, which visit */}
      <div style={{ padding: '14px 18px 0' }}>
        <div className="card" style={{ padding: 13, display: 'flex', alignItems: 'center', gap: 11, background: 'var(--green-50)', borderColor: 'var(--green-100)' }}>
          <Avatar name="Diego Marta" size={40} ring />
          <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }}>Diego Marta</div><div style={{ fontSize: 12.5, color: 'var(--green-800)' }}>Marta Lawn &amp; Pool · weekly pool</div></div>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--green-700)' }}><Icon name="shield" size={14} />Approves it</span>
        </div>
      </div>

      {mode === 'reschedule' && (
        <div style={{ padding: '16px 18px 0' }}>
          <SectionHead tone="yellow" icon="calendar" style={{ marginBottom: 12 }}>Next visit · Mon, May 18 · 10 AM</SectionHead>
          <div style={{ display: 'grid', gap: 9 }}>
            {slots.map(sl => {
              const on = !custom && slot === sl;
              return (
                <button key={sl} onClick={() => { setSlot(sl); setCustom(false); }} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderRadius: 'var(--radius-lg)', border: on ? '2px solid var(--green-500)' : '1.5px solid var(--ink-100)', background: on ? 'var(--green-50)' : '#fff', cursor: 'pointer', textAlign: 'left' }}>
                  <Icon name={sl.includes('Skip') ? 'x' : sl.includes('Keep') ? 'check-circle' : 'calendar'} size={20} style={{ color: on ? 'var(--green-700)' : 'var(--ink-400,#A8A498)' }} />
                  <span style={{ flex: 1, fontWeight: 700, fontSize: 14.5 }}>{sl}</span>
                  <span style={{ width: 22, height: 22, borderRadius: '50%', border: on ? 'none' : '2px solid var(--ink-200)', background: on ? 'var(--green-700)' : 'transparent', display: 'grid', placeItems: 'center', color: '#fff' }}>{on && <Icon name="check" size={13} strokeWidth={3} />}</span>
                </button>
              );
            })}
            {/* arbitrary date + time */}
            <button onClick={() => setCustom(c => !c)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderRadius: 'var(--radius-lg)', border: custom ? '2px solid var(--green-500)' : '1.5px dashed var(--ink-200)', background: custom ? 'var(--green-50)' : '#fff', cursor: 'pointer', textAlign: 'left' }}>
              <Icon name="grid" size={20} style={{ color: custom ? 'var(--green-700)' : 'var(--ink-400,#A8A498)' }} />
              <span style={{ flex: 1, fontWeight: 700, fontSize: 14.5 }}>Pick another day &amp; time</span>
              <Icon name="chevron-down" size={18} style={{ color: 'var(--ink-400,#A8A498)', transform: custom ? 'rotate(180deg)' : 'none', transition: 'transform .18s' }} />
            </button>
            {custom && (
              <div style={{ display: 'grid', gap: 10 }}>
                <MiniCalendar value={date} onChange={setDate} />
                <TimeChips value={time} onChange={setTime} />
                {date && time && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: 'var(--green-700)' }}>
                    <Icon name="check-circle" size={15} />Asking for {date} · {time}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* reason */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="message" style={{ marginBottom: 12 }}>{mode === 'reschedule' ? 'Why? Diego sees this' : 'Your message'}</SectionHead>
        {mode === 'reschedule' && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
            {REASONS.map(r => (
              <button key={r} onClick={() => setMsg(r)} style={{ padding: '8px 12px', borderRadius: 99, border: msg === r ? '2px solid var(--green-500)' : '1.5px solid var(--ink-200)', background: msg === r ? 'var(--green-50)' : '#fff', color: msg === r ? 'var(--green-800)' : 'var(--ink-700)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{r}</button>
            ))}
          </div>
        )}
        <textarea value={msg} onChange={e => setMsg(e.target.value)} className="input" rows={3} style={{ resize: 'none', lineHeight: 1.5 }} placeholder="Write to Diego…" />
      </div>
    </Screen>
  );
}

Object.assign(window, { CHEM_LOG, HomeChemistry, HomeRequest });
