// Kayser v2 — High-leverage MVP additions
// Morning brief card · Audit log sheet · Push notification preview ·
// Hold-for-review mode · Real Pause toggle · Offline banner

// ============ MORNING BRIEF ============
// A special "recap" card type that surfaces at the top of the day.
// Appears once per day in the chat thread when Kayser has activity to summarize.
function KxV2MorningBrief({ brief, onOpenItem }) {
  if (!brief) return null;
  return (
    <div style={{ padding: '4px 14px' }}>
      <div style={{
        ...kx2Glass({ borderRadius: 16 }),
        padding: 14, position: 'relative', overflow: 'hidden',
        background: `linear-gradient(135deg, ${KX2.brandSoft} 0%, ${KX2.glass} 60%)`,
        border: `1px solid ${KX2.brand}`,
        boxShadow: '0 8px 24px rgba(124,58,237,.18)',
      }}>
        {/* Eyebrow */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
          <span style={{ fontFamily: KX2.fontMono, fontSize: 10, fontWeight: 700, color: KX2.brand, letterSpacing: 0.6, textTransform: 'uppercase' }}>
            ✦ Morning brief · {brief.date}
          </span>
          <span style={{ flex: 1 }} />
          <span style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3 }}>{brief.t}</span>
        </div>

        {/* Greeting */}
        <div style={{
          fontFamily: KX2.fontBrand, fontSize: 17, fontWeight: 600, color: KX2.ink,
          letterSpacing: -0.2, marginBottom: 4,
        }}>{brief.greeting}</div>
        <div style={{ fontSize: 13, color: KX2.ink2, lineHeight: 1.45, marginBottom: 12 }}>
          {brief.summary}
        </div>

        {/* Counters */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
          {[
            { k: 'NEEDS YOU',    v: brief.needs,      c: KX2.brand },
            { k: 'AUTO-HANDLED', v: brief.handled,    c: KX2.approve },
            { k: 'WATCHING',     v: brief.watching,   c: KX2.warn },
          ].map(s => (
            <div key={s.k} style={{
              flex: 1, padding: '8px 10px', borderRadius: 10,
              background: 'rgba(255,255,255,.04)',
              border: `1px solid ${KX2.glassLine}`,
            }}>
              <div style={{ fontFamily: KX2.fontMono, fontSize: 9, letterSpacing: 0.4, color: KX2.ink3 }}>{s.k}</div>
              <div style={{
                fontFamily: KX2.fontBrand, fontSize: 20, fontWeight: 700, color: s.c,
                fontVariantNumeric: 'tabular-nums', marginTop: 2,
              }}>{s.v}</div>
            </div>
          ))}
        </div>

        {/* Top priorities */}
        {brief.priorities && brief.priorities.length > 0 && (
          <div style={{ display: 'grid', gap: 4, marginBottom: 12 }}>
            {brief.priorities.map((p, i) => (
              <button key={i} onClick={() => onOpenItem?.(p)} style={{
                ...kx2GlassThin({ borderRadius: 8 }),
                padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 8,
                cursor: 'pointer', textAlign: 'left', color: KX2.ink, fontFamily: KX2.fontUI,
              }}>
                <span style={{ width: 5, height: 5, borderRadius: 3, background: p.kind === 'needs' ? KX2.brand : KX2.warn, flexShrink: 0 }} />
                <span style={{ fontSize: 12.5, flex: 1 }}>{p.text}</span>
                <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 10 }}>›</span>
              </button>
            ))}
          </div>
        )}

        {brief.cta && (
          <button style={{
            width: '100%', padding: '10px', borderRadius: 10,
            background: KX2.brand, color: '#fff', border: 'none',
            fontFamily: KX2.fontUI, fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>{brief.cta} →</button>
        )}
      </div>
    </div>
  );
}

const KXV2_MORNING_BRIEF = {
  date: 'Tue Apr 28',
  t: '7:42 AM',
  greeting: 'Morning, Wes.',
  summary: "While you slept I caught up on yesterday. Two things need you this morning; the rest is in hand.",
  needs: 2,
  handled: 4,
  watching: 7,
  priorities: [
    { kind: 'needs',     text: 'Send reminder to Garcia · #1031 · $4,800 · 7d overdue' },
    { kind: 'needs',     text: 'Confirm Williams porch estimate · today 1 PM' },
    { kind: 'watching',  text: '3 invoices crossed 60-day line · $11.2K outstanding' },
  ],
  cta: 'See the day',
};

// ============ AUDIT LOG SHEET ============
// "What did Kayser do for me this week?" — every auto-handled action, filterable.
const KXV2_AUDIT = [
  { t: 'Today 7:42 AM',   kind: 'reschedule',  who: 'Patel · exterior repaint', what: 'Moved from Wed 2 PM to Thu 9 AM',           why: 'Weather rule · 70% rain forecast',         can_undo: true },
  { t: 'Today 6:58 AM',   kind: 'reply',       who: 'New lead · Reyes Bakery',   what: 'Sent intro reply with availability',          why: 'Auto-reply rule · responds within 4 hrs',   can_undo: true },
  { t: 'Today 6:18 AM',   kind: 'log',         who: 'Sherwin Williams receipt',  what: 'Filed to job 1822 expenses',                   why: 'Pattern match · vendor + amount + date',   can_undo: true },
  { t: 'Yesterday 4:21 PM', kind: 'reminder',  who: 'Chen kitchen',              what: 'Sent appointment reminder',                    why: 'Same-day reminder rule',                     can_undo: false },
  { t: 'Yesterday 11:02 AM', kind: 'log',      who: 'Home Depot receipt',         what: 'Filed to job 1827 expenses',                  why: 'Pattern match · matched job by date',      can_undo: false },
  { t: 'Yesterday 9:14 AM', kind: 'reply',     who: 'Jenkins inquiry',            what: 'Replied: not taking new clients until June', why: 'Capacity rule · you set this on Apr 12',   can_undo: false },
  { t: 'Apr 26 3:18 PM',   kind: 'reminder',   who: 'Garcia · #1031',             what: 'Soft nudge at day 5',                          why: 'Reminder rule · invoice >5 days',          can_undo: false },
  { t: 'Apr 26 8:00 AM',   kind: 'brief',      who: 'You',                        what: 'Sent morning brief',                           why: 'Daily brief on',                            can_undo: false },
];

const KXV2_AUDIT_ICONS = {
  reschedule: '◷',
  reply:      '↗',
  log:        '◈',
  reminder:   '◌',
  brief:      '✦',
};

function KxV2AuditSheet({ open, onClose }) {
  const [filter, setFilter] = React.useState('all');
  const groups = ['all', 'reply', 'reminder', 'reschedule', 'log'];
  const filtered = filter === 'all' ? KXV2_AUDIT : KXV2_AUDIT.filter(a => a.kind === filter);

  return (
    <KxV2Sheet open={open} onClose={onClose} title="What I did">
      <div style={{ padding: '8px 14px 0' }}>
        <div style={{ fontSize: 13, color: KX2.ink2, lineHeight: 1.5, marginBottom: 12 }}>
          Every action I took on my own. Tap any to see why — and undo it if recent.
        </div>
        <div style={{
          display: 'flex', gap: 4, overflowX: 'auto', WebkitOverflowScrolling: 'touch',
          paddingBottom: 4, scrollbarWidth: 'none',
        }} className="kx-audit-filters">
          <style>{`.kx-audit-filters::-webkit-scrollbar{display:none}`}</style>
          {groups.map(g => (
            <button key={g} onClick={() => setFilter(g)} style={{
              padding: '5px 12px', borderRadius: 14,
              background: filter === g ? KX2.chipBgActive : 'transparent',
              border: `1px solid ${filter === g ? KX2.glassLine : 'transparent'}`,
              color: filter === g ? KX2.ink : KX2.ink3,
              fontSize: 12, fontWeight: 500, fontFamily: KX2.fontUI, cursor: 'pointer',
              whiteSpace: 'nowrap', flexShrink: 0, textTransform: 'capitalize',
            }}>{g === 'all' ? `All · ${KXV2_AUDIT.length}` : `${g} · ${KXV2_AUDIT.filter(a => a.kind === g).length}`}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '12px 8px 24px' }}>
        {filtered.map((a, i) => (
          <div key={i} style={{
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '10px 12px', display: 'flex', alignItems: 'flex-start', gap: 10,
            marginBottom: 4,
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8, background: KX2.chipBg, color: KX2.ink2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, fontSize: 13, flexShrink: 0,
            }}>{KXV2_AUDIT_ICONS[a.kind] || '·'}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 2 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: KX2.ink, flex: 1, minWidth: 0,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.who}</span>
                <span style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, flexShrink: 0 }}>{a.t}</span>
              </div>
              <div style={{ fontSize: 12.5, color: KX2.ink2, marginBottom: 4 }}>{a.what}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontFamily: KX2.fontMono, fontSize: 10.5, color: KX2.ink3, letterSpacing: 0.2 }}>{a.why}</span>
                <span style={{ flex: 1 }} />
                {a.can_undo && (
                  <button style={{
                    background: 'transparent', border: 'none', color: KX2.brand,
                    fontFamily: KX2.fontMono, fontSize: 10.5, fontWeight: 600,
                    cursor: 'pointer', padding: 0,
                  }}>Undo</button>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </KxV2Sheet>
  );
}

// ============ PUSH NOTIFICATION PREVIEW ============
// A small floating banner that mimics a system push, slides in from top.
// Used to demo the proactive feel without real APNs/FCM.
function KxV2PushBanner({ note, onDismiss, onTap }) {
  React.useEffect(() => {
    if (!note) return;
    const t = setTimeout(onDismiss, 6000);
    return () => clearTimeout(t);
  }, [note, onDismiss]);
  if (!note) return null;
  return (
    <div onClick={onTap} style={{
      position: 'fixed', top: 16, left: '50%', transform: 'translateX(-50%)',
      zIndex: 1500, width: 'min(420px, calc(100% - 24px))',
      ...kx2Glass({ borderRadius: 14 }),
      background: 'rgba(20,14,38,.94)',
      padding: '10px 12px',
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 14px 40px rgba(0,0,0,.5)',
      cursor: 'pointer',
      animation: 'kxv2PushIn 280ms cubic-bezier(.2,.8,.2,1)',
    }}>
      <style>{`@keyframes kxv2PushIn { from { transform: translate(-50%, -120%); opacity: 0; } to { transform: translate(-50%, 0); opacity: 1; } }`}</style>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: `linear-gradient(135deg, ${KX2.brand} 0%, ${KX2.brandDeep} 100%)`,
        color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: KX2.fontBrand, fontWeight: 700, fontSize: 14, flexShrink: 0,
        boxShadow: '0 0 0 1px rgba(255,255,255,.18) inset',
      }}>K</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: KX2.ink, fontWeight: 600,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {note.title || 'Kayser'}
        </div>
        <div style={{ fontSize: 12, color: KX2.ink2, marginTop: 1, lineHeight: 1.35,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {note.body}
        </div>
      </div>
      <button onClick={(e) => { e.stopPropagation(); onDismiss?.(); }} aria-label="Dismiss" style={{
        background: 'transparent', border: 'none', color: KX2.ink3,
        cursor: 'pointer', padding: 4, flexShrink: 0,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
  );
}

// ============ OFFLINE BANNER ============
function KxV2OfflineBanner({ visible }) {
  if (!visible) return null;
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1200,
      background: 'rgba(251,191,36,.18)',
      backdropFilter: 'blur(12px) saturate(140%)',
      WebkitBackdropFilter: 'blur(12px) saturate(140%)',
      borderBottom: `1px solid ${KX2.warn}`,
      padding: '8px 14px', textAlign: 'center',
      fontFamily: KX2.fontUI, fontSize: 12.5, color: KX2.warn, fontWeight: 600,
      animation: 'kxv2SlideDownTop 220ms ease-out',
    }}>
      <style>{`@keyframes kxv2SlideDownTop { from { transform: translateY(-100%); } to { transform: translateY(0); } }`}</style>
      You're offline — I'll catch up when you're back.
    </div>
  );
}

// ============ HOLD-FOR-REVIEW MODE OPTION ON APPROVAL CARDS ============
// Reusable button that schedules a draft for delayed send (asymmetric undo).
function KxV2HoldForReview({ defaultMinutes = 120, onSchedule }) {
  const [minutes, setMinutes] = React.useState(defaultMinutes);
  const options = [
    { v: 30,   label: '30 min' },
    { v: 120,  label: '2 hr' },
    { v: 480,  label: 'Tonight' },
    { v: 1440, label: 'Tomorrow' },
  ];
  return (
    <div style={{
      ...kx2GlassThin({ borderRadius: 10 }),
      padding: '10px 12px', marginTop: 8,
    }}>
      <div style={{
        fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3,
        letterSpacing: 0.4, marginBottom: 8,
      }}>HOLD FOR REVIEW · CANCELABLE</div>
      <div style={{ fontSize: 12.5, color: KX2.ink2, lineHeight: 1.45, marginBottom: 10 }}>
        I'll wait before sending. You can review, edit, or cancel anytime in that window.
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        {options.map(o => (
          <button key={o.v} onClick={() => setMinutes(o.v)} style={{
            flex: 1, padding: '6px 8px', borderRadius: 8,
            background: minutes === o.v ? KX2.brandSoft : 'rgba(255,255,255,.04)',
            border: `1px solid ${minutes === o.v ? KX2.brand : KX2.glassLine}`,
            color: KX2.ink, fontSize: 11.5, fontFamily: KX2.fontUI, cursor: 'pointer',
          }}>{o.label}</button>
        ))}
      </div>
      <button onClick={() => onSchedule?.(minutes)} style={{
        marginTop: 10, width: '100%', padding: '8px',
        background: KX2.brand, color: '#fff', border: 'none', borderRadius: 8,
        fontFamily: KX2.fontUI, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
      }}>Schedule send</button>
    </div>
  );
}

Object.assign(window, {
  KxV2MorningBrief, KXV2_MORNING_BRIEF,
  KxV2AuditSheet, KXV2_AUDIT,
  KxV2PushBanner, KxV2OfflineBanner, KxV2HoldForReview,
});
