// health/HealthKit.jsx
// HealthKit permission flow & ongoing management UI.
//
// Three screens here:
//   1. HealthKitIntro     — pre-permission explainer. Shown once on first
//                           launch (or after Settings → "Connect Apple Health").
//                           Bedtime gradient hero + 4 category rows + CTA.
//   2. HealthKitSheet     — the system sheet itself (Apple-owned). We mock it
//                           so the prototype reads end-to-end.
//   3. HealthKitManage    — long-lived settings screen. Per-category state,
//                           background-sync toggle, last sync, retry, sign out.
//
// Also exports HealthPartial — overview with a partial-permission banner.

// ─────────────────────────────────────────────────────────────
// 1. INTRO — explainer before the system prompt
// ─────────────────────────────────────────────────────────────
function HealthKitIntro({ dark = false }) {
  const cats = [
    { ic: 'moon',       c: 'var(--io-sleep)',     t: 'Sleep',     b: 'Asleep, in bed, sleep stages, time in bed' },
    { ic: 'heart',      c: 'var(--io-heart)',     t: 'Heart',     b: 'Resting, walking and active heart rate' },
    { ic: 'activity',   c: 'var(--io-activity)',  t: 'Activity',  b: 'Steps, distance, exercise and stand minutes' },
    { ic: 'brain',      c: 'var(--io-indigo)',    t: 'Mindfulness',b: 'Mindful minutes — used in cognitive forecast' },
  ];
  return (
    <FrameScreen dark={dark}>
      {/* gradient header — half-bleed at top */}
      <div style={{
        position: 'relative',
        background: 'var(--io-grad-bedtime-deep)',
        padding: '92px 24px 32px',
        color: '#fff', overflow: 'hidden',
      }}>
        {/* tiny stars layer */}
        <div style={{
          position: 'absolute', inset: 0, opacity: 0.7, pointerEvents:'none',
          background: `
            radial-gradient(1.2px 1.2px at 18% 30%, #fff 50%, transparent 51%),
            radial-gradient(1.2px 1.2px at 28% 70%, rgba(255,255,255,.7) 50%, transparent 51%),
            radial-gradient(1.2px 1.2px at 70% 25%, rgba(255,255,255,.6) 50%, transparent 51%),
            radial-gradient(1.2px 1.2px at 84% 60%, rgba(255,255,255,.5) 50%, transparent 51%),
            radial-gradient(1.2px 1.2px at 50% 85%, rgba(255,255,255,.5) 50%, transparent 51%)`
        }}/>
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 20 }}>
          {/* Health glyph in a soft halo */}
          <div style={{
            width: 64, height: 64, borderRadius: 18,
            background: 'rgba(255,255,255,.12)',
            border: '1px solid rgba(255,255,255,.16)',
            display: 'grid', placeItems: 'center',
            color: '#fff',
          }}>
            <Icon name="heart" size={32} stroke={2.4}/>
          </div>
          <div>
            <div className="eyebrow" style={{ color: 'rgba(255,255,255,.65)' }}>Connect Apple Health</div>
            <div className="t1" style={{ color: '#fff', marginTop: 6, letterSpacing: -0.5 }}>
              Your body, on the same page.
            </div>
            <div className="bd" style={{ color: 'rgba(255,255,255,.7)', marginTop: 8, lineHeight: 1.4 }}>
              Ordentus reads sleep, heart rate, activity and mindfulness from Apple Health and syncs them to your server in the background.
            </div>
          </div>
        </div>
      </div>

      {/* category list */}
      <div style={{ padding: '22px 16px 0' }}>
        <div className="cp" style={{ color: 'var(--io-label-secondary)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600, padding: '0 4px 8px' }}>What we read</div>
        <div className="card" style={{ padding: 4 }}>
          {cats.map((r, i) => (
            <div key={r.t} className="lrow" style={{ paddingTop: 13, paddingBottom: 13 }}>
              <div className="li-ic" style={{ background: r.c }}><Icon name={r.ic} size={16} stroke={2.2}/></div>
              <div className="li-ti" style={{ fontSize: 16 }}>
                {r.t}
                <div className="cp" style={{ color: 'var(--io-label-secondary)', marginTop: 2, fontWeight: 400, lineHeight: 1.35 }}>{r.b}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* footer assurances */}
      <div style={{ padding: '18px 24px 0' }}>
        <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
          <div style={{ color: 'var(--io-green)', marginTop: 1 }}><Icon name="lock" size={16} stroke={2.2}/></div>
          <div className="fn" style={{ color: 'var(--io-label-secondary)', lineHeight: 1.4 }}>
            Ordentus never writes back to Apple Health. Data is sent only to your own server — the one you signed into.
          </div>
        </div>
      </div>

      {/* CTAs */}
      <div style={{ padding: '24px 16px 0', display: 'grid', gap: 10 }}>
        <button style={{
          border: 'none', cursor: 'pointer',
          background: 'var(--io-blue)', color: '#fff',
          borderRadius: 14, padding: '15px 18px',
          fontSize: 17, fontWeight: 600, letterSpacing: -0.4,
        }}>Continue</button>
        <button style={{
          border: 'none', cursor: 'pointer', background: 'transparent',
          color: 'var(--io-blue)', fontSize: 15, fontWeight: 500, letterSpacing: -0.24,
          padding: '8px 12px',
        }}>Not now — I'll connect later in Settings</button>
      </div>

      <div className="scroll-pad"/>
    </FrameScreen>
  );
}
window.HealthKitIntro = HealthKitIntro;

// ─────────────────────────────────────────────────────────────
// 2. SYSTEM SHEET — Apple-owned. We mock it for the prototype only,
//                   so the flow reads end-to-end.
// ─────────────────────────────────────────────────────────────
function HealthKitSheet({ dark = false }) {
  const cats = [
    { name: 'Sleep Analysis', state: 'allow' },
    { name: 'Heart Rate', state: 'allow' },
    { name: 'Resting Heart Rate', state: 'allow' },
    { name: 'Steps', state: 'allow' },
    { name: 'Distance Walking + Running', state: 'allow' },
    { name: 'Mindful Minutes', state: 'allow' },
    { name: 'Active Energy', state: 'allow' },
  ];

  // dimmed parent
  return (
    <FrameScreen dark={dark}>
      <div style={{ opacity: 0.35, filter: 'blur(2px)' }}>
        <BigTitle
          title="Summary"
          leading={<div style={{ paddingLeft: 4, fontSize: 15, fontWeight: 600, color: 'var(--io-label-secondary)', whiteSpace:'nowrap' }}>
            <span style={{ color: 'var(--io-label)' }}>Sunday</span> · Mar 16
          </div>}
          trailing={<><PillBtn><Icon name="search" size={18} stroke={2.4}/></PillBtn><Avatar initial="L"/></>}
        />
      </div>
      <div style={{
        position: 'absolute', inset: 0,
        background: dark ? 'rgba(0,0,0,0.55)' : 'rgba(0,0,0,0.25)',
        backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      }}/>

      {/* iOS Health permission sheet — full sheet, white in light, dark grouped in dark */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 44, bottom: 0,
        background: dark ? '#000' : '#F2F2F7',
        borderRadius: '14px 14px 0 0',
        overflow: 'hidden',
      }}>
        {/* Header — Cancel · Health · ... */}
        <div className="between" style={{ padding: '10px 16px', background: dark ? '#1C1C1E' : '#F2F2F7' }}>
          <span style={{ color: 'var(--io-red)', fontSize: 17, letterSpacing: -0.4 }}>Cancel</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'linear-gradient(135deg, #FF3B30, #FF2D55)', display: 'grid', placeItems: 'center' }}>
              <Icon name="heart" size={12} stroke={3}/>
            </div>
            <span className="hd">Health Access</span>
          </div>
          <span style={{ width: 50 }}/>
        </div>

        {/* Intro card */}
        <div style={{ padding: '12px 16px 0' }}>
          <div style={{
            background: dark ? '#1C1C1E' : '#fff',
            borderRadius: 12, padding: '14px 16px',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 9,
              background: 'linear-gradient(135deg, #5E5CE6, #AF52DE)',
              color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <Icon name="moon" size={20} stroke={2.4}/>
            </div>
            <div>
              <div className="hd" style={{ fontSize: 15 }}>Ordentus</div>
              <div className="cp" style={{ color: 'var(--io-label-secondary)' }}>would like to access your Health data</div>
            </div>
          </div>
        </div>

        <div style={{ padding: '20px 24px 6px' }}>
          <div className="cp" style={{ color: 'var(--io-label-secondary)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600 }}>Turn On All</div>
        </div>
        <div style={{ padding: '0 16px' }}>
          <div style={{
            background: dark ? '#1C1C1E' : '#fff',
            borderRadius: 12, padding: '14px 16px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <span className="bd">Turn on all categories</span>
            <div style={{
              width: 51, height: 31, borderRadius: 999,
              background: 'var(--io-green)', position: 'relative', flexShrink: 0,
            }}>
              <div style={{
                position: 'absolute', top: 2, left: 22,
                width: 27, height: 27, borderRadius: '50%', background: '#fff',
                boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
              }}/>
            </div>
          </div>
        </div>

        <div style={{ padding: '20px 24px 6px' }}>
          <div className="cp" style={{ color: 'var(--io-label-secondary)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600 }}>Allow "Ordentus" to read</div>
        </div>
        <div style={{ padding: '0 16px' }}>
          <div style={{ background: dark ? '#1C1C1E' : '#fff', borderRadius: 12, overflow: 'hidden' }}>
            {cats.map((r, i) => (
              <div key={r.name} style={{
                padding: '12px 16px',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                borderBottom: i < cats.length - 1 ? `0.5px solid ${dark ? 'rgba(84,84,88,0.65)' : 'rgba(60,60,67,0.12)'}` : 'none',
              }}>
                <span className="bd" style={{ fontSize: 16 }}>{r.name}</span>
                <div style={{
                  width: 51, height: 31, borderRadius: 999,
                  background: 'var(--io-green)', position: 'relative', flexShrink: 0,
                }}>
                  <div style={{
                    position: 'absolute', top: 2, left: 22,
                    width: 27, height: 27, borderRadius: '50%', background: '#fff',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
                  }}/>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom action */}
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 16px 32px',
          background: dark ? '#000' : '#F2F2F7' }}>
          <button style={{
            width: '100%', border: 'none', cursor: 'pointer',
            background: 'var(--io-blue)', color: '#fff',
            borderRadius: 14, padding: '15px 18px',
            fontSize: 17, fontWeight: 600, letterSpacing: -0.4,
          }}>Allow</button>
        </div>
      </div>
    </FrameScreen>
  );
}
window.HealthKitSheet = HealthKitSheet;

// ─────────────────────────────────────────────────────────────
// 3. MANAGE — long-lived settings screen
// ─────────────────────────────────────────────────────────────
function HealthKitManage({ dark = false, partial = false }) {
  const cats = partial
    ? [
        { ic: 'moon',     c: 'var(--io-sleep)',     t: 'Sleep',         s: 'Reading',  on: true,  detail: 'Last sample 5:06 AM' },
        { ic: 'heart',    c: 'var(--io-heart)',     t: 'Heart rate',    s: 'Reading',  on: true,  detail: 'Last sample 9:14 AM' },
        { ic: 'activity', c: 'var(--io-activity)',  t: 'Activity',      s: 'Not granted', on: false, detail: 'Steps and exercise unavailable' },
        { ic: 'brain',    c: 'var(--io-indigo)',    t: 'Mindfulness',   s: 'Reading',  on: true,  detail: 'Last sample yesterday 7:30 PM' },
      ]
    : [
        { ic: 'moon',     c: 'var(--io-sleep)',     t: 'Sleep',         s: 'Reading',  on: true,  detail: 'Last sample 5:06 AM' },
        { ic: 'heart',    c: 'var(--io-heart)',     t: 'Heart rate',    s: 'Reading',  on: true,  detail: 'Last sample 9:14 AM' },
        { ic: 'activity', c: 'var(--io-activity)',  t: 'Activity',      s: 'Reading',  on: true,  detail: 'Last sample 8:32 AM' },
        { ic: 'brain',    c: 'var(--io-indigo)',    t: 'Mindfulness',   s: 'Reading',  on: true,  detail: 'Last sample yesterday 7:30 PM' },
      ];

  return (
    <FrameScreen dark={dark}>
      <InlineNav back="Settings" title="Apple Health"/>

      {/* Hero status */}
      <div style={{ padding: '8px 16px 0' }}>
        <div className="card padded" style={{ padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: partial ? 'rgba(255,149,0,0.16)' : 'rgba(52,199,89,0.16)',
            color: partial ? 'var(--io-orange)' : 'var(--io-green)',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <Icon name={partial ? 'alert' : 'check'} size={22} stroke={2.4}/>
          </div>
          <div style={{ flex: 1 }}>
            <div className="hd" style={{ fontSize: 15 }}>
              {partial ? 'Some categories aren\'t shared' : 'Syncing in the background'}
            </div>
            <div className="cp" style={{ color: 'var(--io-label-secondary)', marginTop: 2, lineHeight: 1.35 }}>
              {partial
                ? 'Open Apple Health to share the missing categories with Ordentus.'
                : 'Last sync 14 minutes ago · 1,284 samples in the last 24h.'}
            </div>
          </div>
        </div>
      </div>

      <SectionHead label="Categories"/>
      <div style={{ padding: '0 16px' }}>
        <div className="card" style={{ padding: 4 }}>
          {cats.map((r, i) => (
            <div key={r.t} className="lrow" style={{ paddingTop: 12, paddingBottom: 12 }}>
              <div className="li-ic" style={{ background: r.c }}><Icon name={r.ic} size={16} stroke={2.2}/></div>
              <div className="li-ti" style={{ fontSize: 16 }}>
                {r.t}
                <div className="cp" style={{ color: r.on ? 'var(--io-label-secondary)' : 'var(--io-orange)', marginTop: 2, fontWeight: 400 }}>
                  {r.s} · {r.detail}
                </div>
              </div>
              {r.on
                ? <div style={{
                    width: 51, height: 31, borderRadius: 999,
                    background: 'var(--io-green)', position: 'relative', flexShrink: 0,
                  }}>
                    <div style={{
                      position: 'absolute', top: 2, left: 22,
                      width: 27, height: 27, borderRadius: '50%', background: '#fff',
                      boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
                    }}/>
                  </div>
                : <span className="bd" style={{ color: 'var(--io-blue)', fontWeight: 500 }}>Open Health</span>
              }
            </div>
          ))}
        </div>
      </div>

      <SectionHead label="Background sync"/>
      <div style={{ padding: '0 16px' }}>
        <div className="card" style={{ padding: 4 }}>
          <div className="lrow">
            <div className="li-ti">Live sync</div>
            <div style={{
              width: 51, height: 31, borderRadius: 999,
              background: 'var(--io-green)', position: 'relative', flexShrink: 0,
            }}>
              <div style={{ position: 'absolute', top: 2, left: 22, width: 27, height: 27, borderRadius: '50%', background: '#fff', boxShadow: '0 2px 4px rgba(0,0,0,0.2)' }}/>
            </div>
          </div>
          <div className="lrow">
            <div className="li-ti">Cellular sync</div>
            <div style={{
              width: 51, height: 31, borderRadius: 999,
              background: dark ? '#39393D' : '#E9E9EA', position: 'relative', flexShrink: 0,
            }}>
              <div style={{ position: 'absolute', top: 2, left: 2, width: 27, height: 27, borderRadius: '50%', background: '#fff', boxShadow: '0 2px 4px rgba(0,0,0,0.2)' }}/>
            </div>
          </div>
          <div className="lrow">
            <div className="li-ti">Server</div>
            <div className="li-de" data-num>portal.l.workers.dev</div>
          </div>
          <div className="lrow">
            <div className="li-ti">Last sync</div>
            <div className="li-de">14 min ago · 1,284 samples</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '16px 16px 0', display: 'grid', gap: 10 }}>
        <button style={{
          border: 'none', cursor: 'pointer',
          background: 'var(--io-bg-elev)', color: 'var(--io-blue)',
          borderRadius: 14, padding: '14px 18px',
          fontSize: 17, fontWeight: 500, letterSpacing: -0.4,
        }}>Sync now</button>
        <button style={{
          border: 'none', cursor: 'pointer',
          background: 'var(--io-bg-elev)', color: 'var(--io-red)',
          borderRadius: 14, padding: '14px 18px',
          fontSize: 17, fontWeight: 500, letterSpacing: -0.4,
        }}>Disconnect Apple Health</button>
      </div>

      <div style={{ padding: '14px 24px 0' }}>
        <div className="fn" style={{ color: 'var(--io-label-tertiary)', lineHeight: 1.4 }}>
          Ordentus reads from Apple Health and writes to your own server only. Permissions can also be changed anytime in <span style={{ color: 'var(--io-blue)' }}>Settings → Health → Data Access &amp; Devices → Ordentus</span>.
        </div>
      </div>

      <div className="scroll-pad"/>
      <TabBar active="settings"/>
    </FrameScreen>
  );
}
window.HealthKitManage = HealthKitManage;

// ─────────────────────────────────────────────────────────────
// 4. PARTIAL — Overview with a permission banner
// ─────────────────────────────────────────────────────────────
function HealthKitPartial({ dark = false }) {
  return (
    <HealthOverview
      dark={dark}
      banner={
        <Banner kind="warn" icon="alert" action="Fix">
          <div style={{ fontWeight: 600 }}>Activity not shared</div>
          <div style={{ fontSize: 12, opacity: 0.85 }}>Steps and exercise are missing from Apple Health.</div>
        </Banner>
      }
    />
  );
}
window.HealthKitPartial = HealthKitPartial;
