// Healify — shared sheets, confirms, and a couple of detail screens for the
// Settings / Account / Billing stacks. Loaded AFTER screens-account.jsx so
// these helpers are available when the parent screens render.

const { useState: useStateAX, useEffect: useEffectAX, useRef: useRefAX } = React;

// ── HSheet -----------------------------------------------------------------
// Bottom-sheet shell. Tap outside or the X to close. Renders into the iOS
// frame's body (position: fixed against the viewport), animated up from the
// bottom edge.
function HSheet({ title, onClose, children, maxHeight = '88%' }) {
  useEffectAX(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(3,4,13,0.42)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      animation: 'hSheetBg 200ms ease-out',
    }}>
      <style>{`
        @keyframes hSheetBg { from { opacity: 0; } }
        @keyframes hSheetIn { from { transform: translateY(100%); } }
      `}</style>
      <div onClick={e => e.stopPropagation()} style={{
        background: H.bg, borderRadius: '24px 24px 0 0', width: '100%', maxWidth: 460,
        padding: '14px 20px 28px', maxHeight, overflowY: 'auto',
        animation: 'hSheetIn 280ms ease-out',
      }}>
        <div style={{ width: 40, height: 4, background: H.border, borderRadius: 999, margin: '4px auto 14px' }}/>
        {title && (
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginBottom: 14 }}>{title}</div>
        )}
        {children}
      </div>
    </div>
  );
}

// ── HEditFieldSheet --------------------------------------------------------
// Single-field editor. Pre-fills with `value`, calls onSave(newValue) on Save.
function HEditFieldSheet({ title, label, value, placeholder, type = 'text', onSave, onClose, hint }) {
  const [v, setV] = useStateAX(value || '');
  const ref = useRefAX(null);
  useEffectAX(() => {
    const t = setTimeout(() => ref.current && ref.current.focus(), 240);
    return () => clearTimeout(t);
  }, []);
  return (
    <HSheet title={title} onClose={onClose}>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3, margin: '0 2px 6px' }}>{label}</div>
      <HCard style={{ padding: '14px 16px', marginBottom: hint ? 8 : 18 }}>
        <input
          ref={ref}
          type={type}
          value={v}
          onChange={e => setV(e.target.value)}
          placeholder={placeholder}
          style={{ width: '100%', border: 0, outline: 'none', background: 'transparent', fontFamily: H.body, fontSize: 16 }}
        />
      </HCard>
      {hint && (
        <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, lineHeight: 1.5, margin: '0 2px 18px' }}>{hint}</div>
      )}
      <HPrimaryButton onClick={() => onSave(v)}>Save</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={onClose}>Cancel</HPrimaryButton>
    </HSheet>
  );
}

// ── HDateSheet -------------------------------------------------------------
// Native date picker via <input type="date">. We render a single input row
// rather than custom wheels, so the device's native picker handles input.
function HDateSheet({ title, value, onSave, onClose }) {
  const [v, setV] = useStateAX(value || '');
  return (
    <HSheet title={title} onClose={onClose}>
      <HCard style={{ padding: '14px 16px', marginBottom: 18 }}>
        <input
          type="date"
          value={v}
          onChange={e => setV(e.target.value)}
          style={{ width: '100%', border: 0, outline: 'none', background: 'transparent', fontFamily: H.body, fontSize: 16 }}
        />
      </HCard>
      <HPrimaryButton onClick={() => onSave(v)}>Save</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={onClose}>Cancel</HPrimaryButton>
    </HSheet>
  );
}

// ── HConfirmSheet ----------------------------------------------------------
// Destructive or neutral confirm pattern. Big-glyph header, body copy, two
// buttons. `destructive` flips the primary button to red.
function HConfirmSheet({ icon, title, body, primary = 'Confirm', cancel = 'Cancel', destructive = false, onConfirm, onClose }) {
  return (
    <HSheet onClose={onClose}>
      <div style={{ padding: '6px 4px 0', textAlign: 'center' }}>
        {icon && (
          <div style={{
            width: 64, height: 64, borderRadius: 999, margin: '0 auto 14px',
            background: destructive ? 'var(--danger-50, #FFE9E5)' : 'var(--quartz-cream-bg)',
            display: 'grid', placeItems: 'center',
          }}>
            {icon}
          </div>
        )}
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, letterSpacing: -0.3, marginBottom: 8 }}>{title}</div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, lineHeight: 1.55, marginBottom: 22 }}>{body}</div>
      </div>
      {destructive ? (
        <button onClick={onConfirm} style={{
          width: '100%', padding: '14px 20px', borderRadius: 999, border: 0, cursor: 'pointer',
          background: H.danger, color: '#fff',
          fontFamily: H.body, fontWeight: 500, fontSize: 15,
        }}>{primary}</button>
      ) : (
        <HPrimaryButton onClick={onConfirm}>{primary}</HPrimaryButton>
      )}
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={onClose}>{cancel}</HPrimaryButton>
    </HSheet>
  );
}

// ── HPermissionSheet -------------------------------------------------------
// Provider connect / permission flow. Lists what gets read, big primary CTA.
function HPermissionSheet({ provider, perms, onAllow, onClose }) {
  return (
    <HSheet title={'Connect ' + provider.name} onClose={onClose}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '4px 4px 16px' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 16,
          background: provider.bg || 'var(--quartz-cream-bg)', color: provider.fg || H.fg1,
          display: 'grid', placeItems: 'center',
          fontFamily: H.body, fontWeight: 600, fontSize: 20,
        }}>
          {provider.icon}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16 }}>{provider.name}</div>
          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>Healify will read, never write.</div>
        </div>
      </div>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3, margin: '0 2px 8px' }}>What Anna will see</div>
      <HCard style={{ padding: 0, marginBottom: 18 }}>
        {perms.map((p, i, arr) => (
          <div key={i} style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={H.success} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
            <div style={{ fontFamily: H.body, fontSize: 14 }}>{p}</div>
          </div>
        ))}
      </HCard>
      <HPrimaryButton onClick={onAllow}>Allow access</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={onClose}>Not now</HPrimaryButton>
    </HSheet>
  );
}

// ── ReceiptDetailScreen ----------------------------------------------------
// Tapping a receipt row drills into here.
function ReceiptDetailScreen({ onNavigate, onBack, receipt = {} }) {
  const r = {
    d: 'Mar 12, 2026',
    desc: 'Healify Plus \u00B7 Annual',
    amt: '$89.99',
    s: 'Paid',
    method: 'Visa \u2022 4242',
    invoice: 'HLF-2026-031284',
    period: 'Mar 12, 2026 \u2014 Mar 12, 2027',
    subtotal: '$89.99',
    tax: '$0.00',
    total: '$89.99',
    ...receipt,
  };
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Receipt" />

      <HCard style={{ padding: 20, borderRadius: 22, marginBottom: 14, textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: 999, margin: '0 auto 10px', background: 'var(--success-50, #E6F8EA)', display: 'grid', placeItems: 'center' }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={H.success} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
        </div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4 }}>{r.amt}</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 4 }}>{r.desc}</div>
        <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 2 }}>{r.d}</div>
      </HCard>

      <HSectionLabel style={{ margin: '12px 4px 10px' }}>Details</HSectionLabel>
      <HCard style={{ padding: 0, marginBottom: 14 }}>
        {[
          { k: 'Invoice', v: r.invoice },
          { k: 'Period', v: r.period },
          { k: 'Payment', v: r.method },
          { k: 'Status', v: r.s },
        ].map((row, i, arr) => (
          <div key={row.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 16px', borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>{row.k}</div>
            <div style={{ fontFamily: H.body, fontSize: 14, fontWeight: 500 }}>{row.v}</div>
          </div>
        ))}
      </HCard>

      <HSectionLabel style={{ margin: '12px 4px 10px' }}>Charges</HSectionLabel>
      <HCard style={{ padding: 0, marginBottom: 22 }}>
        {[
          { k: 'Subtotal', v: r.subtotal },
          { k: 'Tax', v: r.tax },
        ].map((row, i, arr) => (
          <div key={row.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderBottom: '0.5px solid ' + H.border }}>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>{row.k}</div>
            <div style={{ fontFamily: H.body, fontSize: 14 }}>{row.v}</div>
          </div>
        ))}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 16px' }}>
          <div style={{ fontFamily: H.body, fontSize: 14, fontWeight: 500 }}>Total</div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 18 }}>{r.total}</div>
        </div>
      </HCard>

      <HPrimaryButton type="outline" onClick={() => {}}>Download PDF</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={() => onNavigate('contact', { topic: 'billing' })}>Email me a copy</HPrimaryButton>
    </div>
  );
}

Object.assign(window, {
  HSheet, HEditFieldSheet, HDateSheet, HConfirmSheet, HPermissionSheet,
  ReceiptDetailScreen,
});
