// Daily wellness tip card — fetches a Claude-generated self-care prompt
// from /api/healthcare-tip and caches it in localStorage per calendar day.

const WELLNESS_CACHE_KEY = 'norwill.wellnessTip.v2';

function loadCachedTip() {
  try {
    const raw = localStorage.getItem(WELLNESS_CACHE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    const today = new Date().toISOString().slice(0, 10);
    if (parsed.date !== today) return null;
    return parsed;
  } catch { return null; }
}

function saveCachedTip(tip) {
  try { localStorage.setItem(WELLNESS_CACHE_KEY, JSON.stringify(tip)); } catch {}
}

const CATEGORY_META = {
  Breath:      { glyph: '🌬', tint: '#7CD1D8' },
  Movement:    { glyph: '🤸', tint: '#9DEFC5' },
  Hydration:   { glyph: '💧', tint: '#7CD1D8' },
  Boundaries:  { glyph: '🛡', tint: '#FFE3A8' },
  Mind:        { glyph: '🧠', tint: '#C9B8FF' },
  Rest:        { glyph: '🌙', tint: '#9FB4FF' },
  Nourish:     { glyph: '🥗', tint: '#9DEFC5' },
  Connection:  { glyph: '💬', tint: '#FFC9B8' },
};

function WellnessTipCard({ persona, compact }) {
  const [tip, setTip] = React.useState(() => loadCachedTip());
  const [loading, setLoading] = React.useState(!tip);
  const [error, setError] = React.useState(null);
  const [expanded, setExpanded] = React.useState(false);

  React.useEffect(() => {
    if (!expanded) return;
    const onKey = (e) => { if (e.key === 'Escape') setExpanded(false); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [expanded]);

  const fetchTip = React.useCallback(async (force) => {
    setLoading(true); setError(null);
    try {
      const url = force ? '/api/healthcare-tip?refresh=1' : '/api/healthcare-tip';
      const r = await fetch(url);
      if (!r.ok) throw new Error('Tip service returned ' + r.status);
      const data = await r.json();
      setTip(data);
      saveCachedTip(data);
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    if (!tip) fetchTip(false);
  }, [tip, fetchTip]);

  const meta = CATEGORY_META[tip?.category] || CATEGORY_META.Mind;
  const firstName = persona?.name?.split(' ')[0] || 'team';

  if (compact) {
    return (
      <>
      <div
        role="button" tabIndex={0}
        onClick={() => tip && setExpanded(true)}
        onKeyDown={(e) => { if (tip && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setExpanded(true); } }}
        style={{
        padding: '14px 16px', borderRadius: 14,
        background: 'linear-gradient(140deg, #063B42 0%, var(--brand-700) 45%, var(--brand-500) 100%)',
        color: '#fff', position: 'relative', overflow: 'hidden',
        boxShadow: '0 6px 18px rgba(11, 106, 116, 0.22)',
        display: 'flex', alignItems: 'center', gap: 14, minHeight: 88,
        cursor: tip ? 'pointer' : 'default',
        transition: 'transform 120ms ease, box-shadow 120ms ease',
      }}
      onMouseEnter={(e) => { if (tip) { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 10px 24px rgba(11, 106, 116, 0.3)'; } }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '0 6px 18px rgba(11, 106, 116, 0.22)'; }}
      >
        <div style={{ position: 'absolute', top: -30, right: -25, width: 130, height: 130,
          borderRadius: '50%',
          background: `radial-gradient(circle, ${meta.tint}40, transparent 70%)`,
          pointerEvents: 'none' }}/>
        <div style={{
          width: 40, height: 40, borderRadius: 11,
          background: 'rgba(255,255,255,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid rgba(255,255,255,0.25)',
          fontSize: 20, flexShrink: 0, position: 'relative',
        }}>{meta.glyph}</div>
        <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
          <div style={{ fontSize: 10.5, opacity: 0.8, letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700 }}>
            Daily care · {tip?.category || 'Wellness'}
          </div>
          {loading && !tip && (
            <div style={{ fontSize: 13, opacity: 0.85, fontStyle: 'italic', marginTop: 4 }}>
              Pulling today's care prompt…
            </div>
          )}
          {error && !tip && (
            <div style={{ fontSize: 12.5, opacity: 0.9, lineHeight: 1.4, marginTop: 4 }}>
              Couldn't load today's tip.
            </div>
          )}
          {tip && (
            <>
              <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: -0.2, lineHeight: 1.2, marginTop: 2 }}>
                {tip.headline}
              </div>
              <div style={{
                fontSize: 12.5, lineHeight: 1.4, opacity: 0.92, marginTop: 3,
                display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                overflow: 'hidden',
              }}>
                {tip.tip}
              </div>
              <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: 0.06, textTransform: 'uppercase', opacity: 0.7, marginTop: 6 }}>
                Tap to expand ↗
              </div>
            </>
          )}
        </div>
        <button
          onClick={(e) => { e.stopPropagation(); fetchTip(true); }}
          title="New tip"
          style={{
            background: 'rgba(255,255,255,0.14)',
            border: '1px solid rgba(255,255,255,0.22)',
            color: '#fff', borderRadius: 8, padding: '4px 8px',
            fontSize: 12, fontWeight: 600, cursor: 'pointer',
            position: 'relative', alignSelf: 'flex-start', flexShrink: 0,
          }}>↻</button>
      </div>
      {expanded && tip && <WellnessTipModal tip={tip} meta={meta} firstName={firstName} onClose={() => setExpanded(false)}/>}
      </>
    );
  }

  return (
    <div style={{
      padding: 18, borderRadius: 16,
      background: 'linear-gradient(140deg, #063B42 0%, var(--brand-700) 45%, var(--brand-500) 100%)',
      color: '#fff', position: 'relative', overflow: 'hidden',
      boxShadow: '0 8px 24px rgba(11, 106, 116, 0.25)',
    }}>
      <div style={{ position: 'absolute', top: -30, right: -25, width: 130, height: 130,
        borderRadius: '50%',
        background: `radial-gradient(circle, ${meta.tint}40, transparent 70%)`,
        pointerEvents: 'none' }}/>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, position: 'relative' }}>
        <div style={{
          width: 34, height: 34, borderRadius: 10,
          background: 'rgba(255,255,255,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid rgba(255,255,255,0.25)',
          fontSize: 18,
        }}>{meta.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: -0.1, lineHeight: 1.15 }}>
            Daily care for {firstName}
          </div>
          <div style={{ fontSize: 10.5, opacity: 0.75, letterSpacing: 0.06, textTransform: 'uppercase', fontWeight: 600, marginTop: 1 }}>
            {tip?.category || 'Wellness'} · today
          </div>
        </div>
        <button
          onClick={() => fetchTip(true)}
          title="New tip"
          style={{
            background: 'rgba(255,255,255,0.14)',
            border: '1px solid rgba(255,255,255,0.22)',
            color: '#fff', borderRadius: 8, padding: '4px 8px',
            fontSize: 11, fontWeight: 600, cursor: 'pointer',
          }}>↻</button>
      </div>

      <div style={{ position: 'relative', minHeight: 92 }}>
        {loading && !tip && (
          <div style={{ fontSize: 13, opacity: 0.85, fontStyle: 'italic' }}>
            Pulling today's care prompt…
          </div>
        )}
        {error && !tip && (
          <div style={{ fontSize: 12.5, opacity: 0.9, lineHeight: 1.45 }}>
            Couldn't load today's tip ({error}). The dashboard still works — we'll retry tomorrow.
          </div>
        )}
        {tip && (
          <>
            <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: -0.3, lineHeight: 1.2, marginBottom: 8 }}>
              {tip.headline}
            </div>
            <div style={{ fontSize: 13.5, lineHeight: 1.5, opacity: 0.95 }}>
              {tip.tip}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function WellnessTipModal({ tip, meta, firstName, onClose }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(6, 28, 32, 0.55)', backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        animation: 'wellnessFadeIn 160ms ease-out',
      }}>
      <style>{`
        @keyframes wellnessFadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes wellnessRise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'linear-gradient(155deg, #063B42 0%, var(--brand-700) 45%, var(--brand-500) 100%)',
          color: '#fff', borderRadius: 20, padding: 28,
          width: '100%', maxWidth: 540, maxHeight: 'calc(100vh - 60px)', overflow: 'auto',
          position: 'relative', boxShadow: '0 24px 60px rgba(0,0,0,0.35)',
          animation: 'wellnessRise 200ms ease-out',
        }}>
        <div style={{ position: 'absolute', top: -50, right: -40, width: 200, height: 200,
          borderRadius: '50%',
          background: `radial-gradient(circle, ${meta.tint}40, transparent 70%)`,
          pointerEvents: 'none' }}/>

        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 14,
            background: 'rgba(255,255,255,0.14)',
            border: '1px solid rgba(255,255,255,0.22)',
            color: '#fff', borderRadius: 10, width: 32, height: 32,
            fontSize: 16, fontWeight: 600, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>×</button>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18, position: 'relative' }}>
          <div style={{
            width: 48, height: 48, borderRadius: 12,
            background: 'rgba(255,255,255,0.18)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '1px solid rgba(255,255,255,0.25)',
            fontSize: 24,
          }}>{meta.glyph}</div>
          <div>
            <div style={{ fontSize: 10.5, opacity: 0.8, letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700 }}>
              Daily care for {firstName} · {tip.category}
            </div>
            <div style={{ fontSize: 12, opacity: 0.7, marginTop: 2 }}>
              {new Date(tip.date + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
            </div>
          </div>
        </div>

        <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.5, lineHeight: 1.15, margin: '0 0 12px', position: 'relative' }}>
          {tip.headline}
        </h2>

        <p style={{ fontSize: 15, lineHeight: 1.55, opacity: 0.95, margin: '0 0 22px', position: 'relative' }}>
          {tip.tip}
        </p>

        {tip.why && (
          <div style={{
            position: 'relative',
            padding: '14px 16px', borderRadius: 12,
            background: 'rgba(255,255,255,0.08)',
            border: '1px solid rgba(255,255,255,0.12)',
            marginBottom: 22,
          }}>
            <div style={{ fontSize: 10.5, opacity: 0.75, letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>
              Why this matters
            </div>
            <div style={{ fontSize: 13.5, lineHeight: 1.5, opacity: 0.95 }}>
              {tip.why}
            </div>
          </div>
        )}

        {Array.isArray(tip.ideas) && tip.ideas.length > 0 && (
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 10.5, opacity: 0.75, letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700, marginBottom: 10 }}>
              Try one today
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {tip.ideas.map((idea, i) => (
                <li key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 12,
                  padding: '12px 14px', borderRadius: 10,
                  background: 'rgba(255,255,255,0.06)',
                  border: '1px solid rgba(255,255,255,0.1)',
                }}>
                  <div style={{
                    width: 24, height: 24, borderRadius: 7, flexShrink: 0,
                    background: 'rgba(255,255,255,0.15)',
                    border: '1px solid rgba(255,255,255,0.2)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 12, fontWeight: 700,
                  }}>{i + 1}</div>
                  <div style={{ fontSize: 13.5, lineHeight: 1.5, opacity: 0.96 }}>{idea}</div>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { WellnessTipCard });
