// pwa.jsx — install affordances + iOS add-to-home instructions

const PWA_DISMISS_KEY = 'dl_pwa_install_dismissed_v1';
const PWA_IOS_TIPS_KEY = 'dl_pwa_ios_tips_dismissed_v1';

// Hook: tracks install state + canInstall + ios + offlineReady
function usePwaState() {
  const [state, setState] = React.useState(() => ({
    installed: window.__dlPwa?.installed || false,
    canInstall: window.__dlPwa?.canInstall || false,
    isIos: window.__dlPwa?.isIos || false,
    updateReady: false,
    serviceReady: !!navigator.serviceWorker?.controller,
  }));

  React.useEffect(() => {
    const onCanInstall = () => setState(s => ({ ...s, canInstall: true }));
    const onInstalled  = () => setState(s => ({ ...s, installed: true, canInstall: false }));
    const onUpdate     = () => setState(s => ({ ...s, updateReady: true }));
    const onSwCtrl     = () => setState(s => ({ ...s, serviceReady: true }));

    window.addEventListener('pwa:can-install', onCanInstall);
    window.addEventListener('pwa:installed', onInstalled);
    window.addEventListener('pwa:update-ready', onUpdate);

    if (navigator.serviceWorker) {
      navigator.serviceWorker.ready.then(onSwCtrl);
      navigator.serviceWorker.addEventListener('controllerchange', onSwCtrl);
    }
    return () => {
      window.removeEventListener('pwa:can-install', onCanInstall);
      window.removeEventListener('pwa:installed', onInstalled);
      window.removeEventListener('pwa:update-ready', onUpdate);
    };
  }, []);

  const promptInstall = React.useCallback(async () => {
    const dp = window.__dlPwa?.deferredPrompt;
    if (!dp) return false;
    dp.prompt();
    const choice = await dp.userChoice;
    window.__dlPwa.deferredPrompt = null;
    window.__dlPwa.canInstall = false;
    setState(s => ({ ...s, canInstall: false }));
    return choice.outcome === 'accepted';
  }, []);

  return { ...state, promptInstall };
}

// ─────────────────────────────────────────────────────────────
// Install banner — sits below greeting on Home
// ─────────────────────────────────────────────────────────────
function PwaInstallCard({ theme }) {
  const pwa = usePwaState();
  const [dismissed, setDismissed] = React.useState(() => {
    try { return localStorage.getItem(PWA_DISMISS_KEY) === '1'; } catch { return false; }
  });
  const [showIosSheet, setShowIosSheet] = React.useState(false);

  // Hide entirely if already installed/dismissed
  if (pwa.installed || dismissed) return null;
  // Show only when canInstall (Android/desktop Chromium) OR iOS (since no prompt event)
  if (!pwa.canInstall && !pwa.isIos) return null;

  const dismiss = () => {
    try { localStorage.setItem(PWA_DISMISS_KEY, '1'); } catch {}
    setDismissed(true);
  };

  const cta = async () => {
    if (pwa.isIos && !pwa.canInstall) {
      setShowIosSheet(true);
      return;
    }
    const ok = await pwa.promptInstall();
    if (ok) dismiss();
  };

  return (
    <>
      <div style={{ padding: '0 20px 16px' }}>
        <div style={{
          background: theme.raised, border: `1px solid ${theme.rule}`,
          borderRadius: 16, padding: 14,
          display: 'flex', alignItems: 'center', gap: 12,
          position: 'relative', overflow: 'hidden',
        }}>
          {/* tiny app icon */}
          <div style={{
            width: 44, height: 44, borderRadius: 11,
            background: `linear-gradient(135deg, ${theme.surface2}, ${theme.surface} 60%, ${theme.gradEnd})`,
            display: 'flex', alignItems: 'flex-end', justifyContent: 'center', padding: '0 7px 7px',
            flexShrink: 0,
          }}>
            <span style={{ width: 4, height: 11, background: 'rgba(255,255,255,0.5)', borderRadius: 1.5, marginRight: 2 }}/>
            <span style={{ width: 4, height: 17, background: 'rgba(255,255,255,0.75)', borderRadius: 1.5, marginRight: 2 }}/>
            <span style={{ width: 4, height: 24, background: '#FFFFFF', borderRadius: 1.5 }}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: theme.ink, lineHeight: 1.2 }}>
              Install DebtLift
            </div>
            <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 3, lineHeight: 1.3 }}>
              {pwa.isIos && !pwa.canInstall
                ? 'Add to your Home Screen — works offline'
                : 'One-tap install · works offline'}
            </div>
          </div>
          <button onClick={cta} style={{
            padding: '8px 14px', borderRadius: 99,
            background: theme.surface, color: theme.onSurface,
            fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap',
            flexShrink: 0,
          }}>
            {pwa.isIos && !pwa.canInstall ? 'How to' : 'Install'}
          </button>
          <button onClick={dismiss} style={{ color: theme.inkMute, padding: 4, flexShrink: 0 }} aria-label="Dismiss">
            <Icon name="x" size={14} color={theme.inkMute}/>
          </button>
        </div>
      </div>

      {showIosSheet && <PwaIosSheet theme={theme} onClose={() => setShowIosSheet(false)}/>}
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// iOS Add-to-Home-Screen sheet
// ─────────────────────────────────────────────────────────────
function PwaIosSheet({ theme, onClose }) {
  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(10,18,32,0.45)',
        zIndex: 80,
      }}/>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: theme.canvas, zIndex: 81,
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '16px 22px 28px',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.3)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', paddingBottom: 12 }}>
          <div style={{ width: 38, height: 4, borderRadius: 99, background: theme.rule }}/>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div style={{
            width: 54, height: 54, borderRadius: 14,
            background: `linear-gradient(135deg, ${theme.surface2}, ${theme.surface} 60%, ${theme.gradEnd})`,
            display: 'flex', alignItems: 'flex-end', justifyContent: 'center', padding: '0 8px 9px',
          }}>
            <span style={{ width: 5, height: 13, background: 'rgba(255,255,255,0.5)', borderRadius: 2, marginRight: 3 }}/>
            <span style={{ width: 5, height: 20, background: 'rgba(255,255,255,0.75)', borderRadius: 2, marginRight: 3 }}/>
            <span style={{ width: 5, height: 28, background: '#FFFFFF', borderRadius: 2 }}/>
          </div>
          <div style={{ flex: 1 }}>
            <div className="serif" style={{ fontSize: 22, fontWeight: 500, color: theme.ink, lineHeight: 1.1 }}>Install DebtLift</div>
            <div style={{ fontSize: 12.5, color: theme.inkMute, marginTop: 4 }}>Add to your iPhone Home Screen</div>
          </div>
        </div>

        <Step n={1} theme={theme}
          title="Tap the Share button"
          body="In Safari's toolbar — the box with an arrow pointing up."
          extra={<SafariShareGlyph theme={theme}/>}
        />
        <Step n={2} theme={theme}
          title={'Choose "Add to Home Screen"'}
          body="Scroll if needed — there's a small + icon next to it."
          extra={<PlusGlyph theme={theme}/>}
        />
        <Step n={3} theme={theme}
          title={'Tap "Add"'}
          body="DebtLift will appear on your Home Screen like any other app."
          last
        />

        <button onClick={onClose} style={{
          width: '100%', marginTop: 18, padding: '14px',
          background: theme.surface, color: theme.onSurface, borderRadius: 14,
          fontSize: 14, fontWeight: 600,
        }}>Got it</button>
      </div>
    </>
  );
}

function Step({ n, title, body, extra, theme, last }) {
  return (
    <div style={{
      display: 'flex', gap: 12, paddingBottom: last ? 0 : 14, alignItems: 'flex-start',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 99,
        background: theme.surface, color: theme.onSurface,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 600, flexShrink: 0,
        fontFamily: 'Newsreader, serif',
      }}>{n}</div>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink }}>{title}</div>
          {extra}
        </div>
        <div style={{ fontSize: 12.5, color: theme.inkMute, marginTop: 3, lineHeight: 1.4 }}>{body}</div>
      </div>
    </div>
  );
}

function SafariShareGlyph({ theme }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 22, height: 22, borderRadius: 5,
      background: theme.canvas2, border: `1px solid ${theme.rule}`,
    }}>
      <svg width="13" height="14" viewBox="0 0 20 22" fill="none">
        <path d="M10 2v12M10 2L6 6M10 2l4 4" stroke={theme.accent.solid} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M4 11v8a1 1 0 001 1h10a1 1 0 001-1v-8" stroke={theme.accent.solid} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </span>
  );
}

function PlusGlyph({ theme }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 22, height: 22, borderRadius: 5,
      background: theme.canvas2, border: `1px solid ${theme.rule}`,
    }}>
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
        <path d="M12 5v14M5 12h14" stroke={theme.accent.solid} strokeWidth="2" strokeLinecap="round"/>
      </svg>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Tiny "Offline ready" indicator (used in Profile / footer)
// ─────────────────────────────────────────────────────────────
function PwaStatusBadge({ theme }) {
  const pwa = usePwaState();
  if (!pwa.serviceReady && !pwa.installed) return null;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 8px', borderRadius: 99,
      background: theme.accent.soft, color: theme.accent.ink,
      fontSize: 10, fontWeight: 600, letterSpacing: 0.6, textTransform: 'uppercase',
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 99, background: theme.accent.solid }}/>
      {pwa.installed ? 'Installed' : 'Offline ready'}
    </div>
  );
}

Object.assign(window, { usePwaState, PwaInstallCard, PwaIosSheet, PwaStatusBadge });
