// Anna's Wall — components. Requires components.jsx + wall-data.jsx loaded first.
// Globals used from the kit: H, HCard, HAnnaAvatar, HPrimaryButton, HChevron.

// ── helpers ──────────────────────────────────────────────────────────────
function pillarOf(post) { return PILLARS[post.pillarTag] || PILLARS.physical; }
// hex -> rgba
function rgba(hex, a) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${a})`;
}

// ── Pillar chip ────────────────────────────────────────────────────────────
function WallPillarChip({ tag }) {
  const p = PILLARS[tag];
  if (!p) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      background: rgba(p.color, 0.12), color: p.color,
      padding: '4px 10px 4px 8px', borderRadius: 999,
      fontFamily: H.body, fontWeight: 500, fontSize: 11,
      letterSpacing: 0.5, textTransform: 'uppercase', flexShrink: 0,
    }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: p.color }} />
      {p.label}
    </span>
  );
}

// ── Type badge (subtle, top-right) ───────────────────────────────────────────
function WallTypeBadge({ type }) {
  const meta = TYPE_META[type] || { label: type };
  const icon = {
    CHART:       <path d="M4 13l4-4 3 3 5-6" />,
    INSIGHT:     <path d="M9 18h6M10 21h4M12 3a6 6 0 0 1 4 10c-.6.6-1 1.2-1 2H9c0-.8-.4-1.4-1-2A6 6 0 0 1 12 3z" />,
    VOICE_NOTE:  <path d="M12 3a3 3 0 0 1 3 3v5a3 3 0 0 1-6 0V6a3 3 0 0 1 3-3zM5 11a7 7 0 0 0 14 0M12 18v3" />,
    ACHIEVEMENT: <path d="M8 4h8v5a4 4 0 0 1-8 0V4zM6 4H4v2a3 3 0 0 0 3 3M18 4h2v2a3 3 0 0 0-3 3M9 17h6l1 4H8z" />,
  }[type];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      background: H.bgSecondary, color: H.fg3,
      padding: '4px 9px', borderRadius: 999,
      fontFamily: H.body, fontWeight: 500, fontSize: 10.5,
      letterSpacing: 0.5, textTransform: 'uppercase', flexShrink: 0,
    }}>
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
        strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{icon}</svg>
      {meta.label}
    </span>
  );
}

// ── Mini line chart (sparkline + full) ───────────────────────────────────────
const CHART_DATA = {
  'chart://resting-hr':    { pts: [62, 61, 63, 60, 59, 58, 57], unit: 'bpm', kind: 'line', last: '57 bpm' },
  'chart://weight-trend':  { pts: [70.4, 70.1, 69.6, 69.5, 69.4, 69.5, 69.4], unit: 'kg', kind: 'line', last: '69.4 kg' },
};
function WallLineChart({ src, color, height = 150, pad = 14, showAxis = true }) {
  const d = CHART_DATA[src] || CHART_DATA['chart://resting-hr'];
  const pts = d.pts;
  const W = 320, H_ = height;
  const min = Math.min(...pts), max = Math.max(...pts);
  const range = (max - min) || 1;
  const x = i => pad + (i / (pts.length - 1)) * (W - pad * 2);
  const y = v => pad + (1 - (v - min) / range) * (H_ - pad * 2);
  const linePts = pts.map((v, i) => `${x(i)},${y(v)}`).join(' ');
  const area = `M ${x(0)},${H_ - pad} L ` + pts.map((v, i) => `${x(i)},${y(v)}`).join(' L ') + ` L ${x(pts.length - 1)},${H_ - pad} Z`;
  const gid = 'wlc-' + src.replace(/[^a-z]/gi, '');
  return (
    <svg viewBox={`0 0 ${W} ${H_}`} width="100%" height={H_} preserveAspectRatio="none" style={{ display: 'block' }}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity="0.22" />
          <stop offset="1" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {showAxis && [0.25, 0.5, 0.75].map(f => (
        <line key={f} x1={pad} x2={W - pad} y1={pad + f * (H_ - pad * 2)} y2={pad + f * (H_ - pad * 2)}
          stroke="rgba(3,4,13,0.06)" strokeWidth="1" />
      ))}
      <path d={area} fill={`url(#${gid})`} />
      <polyline points={linePts} fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={x(pts.length - 1)} cy={y(pts[pts.length - 1])} r="4.5" fill={color} stroke="#fff" strokeWidth="2.5" />
    </svg>
  );
}

// ── Achievement badge art ─────────────────────────────────────────────────
function WallBadgeArt({ color, size = 'lg' }) {
  const big = size === 'lg';
  const s = big ? 96 : 44;
  return (
    <div style={{
      width: big ? '100%' : s, height: big ? '100%' : s,
      display: 'grid', placeItems: 'center',
      background: big ? rgba(color, 0.08) : rgba(color, 0.14), borderRadius: big ? 0 : 14,
    }}>
      <svg width={s} height={s} viewBox="0 0 96 96" fill="none">
        <circle cx="48" cy="40" r="26" fill={rgba(color, 0.16)} />
        <circle cx="48" cy="40" r="26" stroke={color} strokeWidth="3" />
        <path d="M40 40l6 6 12-12" stroke={color} strokeWidth={big ? 4 : 5} strokeLinecap="round" strokeLinejoin="round" fill="none" />
        <path d="M34 60l-5 18 19-9 19 9-5-18" stroke={color} strokeWidth="3" strokeLinejoin="round" fill={rgba(color, 0.10)} />
      </svg>
    </div>
  );
}

// ── Voice waveform / player ──────────────────────────────────────────────
function WallVoiceArt({ color, full = false }) {
  const bars = full ? 38 : 9;
  const heights = Array.from({ length: bars }, (_, i) => 0.28 + 0.72 * Math.abs(Math.sin(i * 1.3) * Math.cos(i * 0.4)));
  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex', alignItems: 'center',
      justifyContent: 'center', gap: full ? 4 : 2.5, padding: full ? '0 16px' : 6,
      background: full ? rgba(color, 0.06) : rgba(color, 0.14), borderRadius: full ? 0 : 14,
    }}>
      {heights.map((h, i) => (
        <span key={i} style={{
          width: full ? 4 : 3, height: `${Math.round(h * (full ? 64 : 30))}px`,
          minHeight: 4, borderRadius: 999, background: color,
          opacity: full ? (i < 14 ? 1 : 0.32) : 0.9,
        }} />
      ))}
    </div>
  );
}

// ── Card media thumbnail (64×64) ───────────────────────────────────────────
function WallMiniMedia({ post }) {
  const p = pillarOf(post);
  if (!post.mediaUrl) return null;
  let inner;
  if (post.type === 'CHART') inner = (
    <div style={{ width: '100%', height: '100%', padding: '10px 2px', boxSizing: 'border-box', background: rgba(p.color, 0.10) }}>
      <WallLineChart src={post.mediaUrl} color={p.color} height={44} pad={6} showAxis={false} />
    </div>
  );
  else if (post.type === 'ACHIEVEMENT') inner = <WallBadgeArt color={p.color} size="sm" />;
  else if (post.type === 'VOICE_NOTE') inner = <WallVoiceArt color={p.color} />;
  return (
    <div style={{
      width: 64, height: 64, borderRadius: 14, overflow: 'hidden', flexShrink: 0,
      position: 'relative', boxShadow: 'inset 0 0 0 1px rgba(3,4,13,0.04)',
    }}>
      {inner}
      {post.type === 'VOICE_NOTE' && (
        <div style={{
          position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
        }}>
          <div style={{ width: 26, height: 26, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', boxShadow: '0 1px 4px rgba(3,4,13,0.18)' }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill={p.color}><path d="M7 5v14l11-7z" /></svg>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Reaction summary (card, read-only) ──────────────────────────────────────
function WallReactionSummary({ reactions, userReaction }) {
  const shown = REACTIONS.filter(r => reactions[r.key] > 0 || r.key === userReaction);
  const total = Object.values(reactions).reduce((a, b) => a + b, 0);
  if (total === 0) return (
    <span style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg3 }}>Be the first to react</span>
  );
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {shown.slice(0, 4).map(r => {
        const mine = r.key === userReaction;
        return (
          <span key={r.key} style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
            <span className={'wall-rx' + (mine ? ' mine' : '')} style={{ fontSize: 14 }}>{r.emoji}</span>
            <span style={{ fontFamily: H.body, fontSize: 12.5, fontWeight: mine ? 600 : 400, color: mine ? H.fg1 : H.fg2 }}>{reactions[r.key]}</span>
          </span>
        );
      })}
    </div>
  );
}

// ── Unread dot ──────────────────────────────────────────────────────────────
function UnreadDot() {
  return <span style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--brand-orange-vibey)', flexShrink: 0, boxShadow: '0 0 0 3px rgba(255,105,66,0.16)' }} />;
}

// ── PostCard ─────────────────────────────────────────────────────────────────
function WallPostCard({ post, onOpen, userReaction, unreadStyle = 'tint', density = 'comfortable' }) {
  const p = pillarOf(post);
  const unread = post.readAt === null;
  const compact = density === 'compact';
  const pad = compact ? 14 : 16;
  const preview = (post.annaCommentary || '').replace(/\n+/g, ' ');

  const tint = unread && unreadStyle === 'tint';
  const accent = unread && unreadStyle === 'accent';

  return (
    <HCard onClick={onOpen} style={{
      padding: 0, borderRadius: 20, overflow: 'hidden',
      position: 'relative',
      background: tint ? 'linear-gradient(180deg, rgba(255,244,240,0.7), #FFFFFF 60%)' : '#fff',
      boxShadow: unread
        ? '0 2px 10px rgba(49,31,105,0.07), 0 1px 2px rgba(3,4,13,0.04)'
        : '0 1px 2px rgba(3,4,13,0.05)',
    }}>
      {accent && <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: 'var(--brand-orange-vibey)' }} />}
      <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: compact ? 9 : 11 }}>
        {/* byline row */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <HAnnaAvatar size={32} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1, minWidth: 0 }}>
            <span style={{ fontFamily: H.body, fontWeight: 600, fontSize: 14.5, color: H.fg1, letterSpacing: -0.2 }}>Anna</span>
            {unread && unreadStyle !== 'none' && <UnreadDot />}
          </div>
          <WallTypeBadge type={post.type} />
        </div>

        {/* content row */}
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 7 }}>
            <div><WallPillarChip tag={post.pillarTag} /></div>
            <div style={{
              fontFamily: H.body, fontWeight: 600, fontSize: 16.5, lineHeight: 1.28,
              color: H.fg1, letterSpacing: -0.3,
              display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
            }}>{post.caption}</div>
            {!compact && (
              <div style={{
                fontFamily: H.body, fontSize: 13.5, lineHeight: 1.45, color: H.fg2, letterSpacing: -0.1,
                display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden',
              }}>{preview}</div>
            )}
          </div>
          {post.mediaUrl && <WallMiniMedia post={post} />}
        </div>

        {/* footer */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: compact ? 1 : 3 }}>
          <WallReactionSummary reactions={post.reactions} userReaction={userReaction} />
          <span style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, flexShrink: 0 }}>{relativeTime(post.createdAt)}</span>
        </div>
      </div>
    </HCard>
  );
}

// ── Skeleton ───────────────────────────────────────────────────────────────
function WallPostCardSkeleton() {
  const Bar = ({ w, h = 12, r = 6, mt = 0 }) => (
    <div className="wall-shimmer" style={{ width: w, height: h, borderRadius: r, marginTop: mt }} />
  );
  return (
    <div style={{ background: '#fff', borderRadius: 20, padding: 16, boxShadow: '0 1px 2px rgba(3,4,13,0.05)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
        <div className="wall-shimmer" style={{ width: 32, height: 32, borderRadius: 999 }} />
        <Bar w={54} h={12} />
        <div style={{ marginLeft: 'auto' }}><Bar w={64} h={20} r={999} /></div>
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 14 }}>
        <div style={{ flex: 1 }}>
          <Bar w={84} h={18} r={999} />
          <Bar w="92%" h={15} mt={10} />
          <Bar w="78%" h={15} mt={8} />
          <Bar w="96%" h={11} mt={12} />
          <Bar w="88%" h={11} mt={7} />
        </div>
        <div className="wall-shimmer" style={{ width: 64, height: 64, borderRadius: 14 }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14 }}>
        <Bar w={120} h={12} />
        <Bar w={56} h={12} />
      </div>
    </div>
  );
}

// ── Empty state ──────────────────────────────────────────────────────────────
function WallEmptyState() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '72px 30px 40px' }}>
      <div style={{ position: 'relative', width: 96, height: 96, display: 'grid', placeItems: 'center', marginBottom: 26 }}>
        <span style={{ position: 'absolute', inset: 0, borderRadius: 999, background: 'var(--brand-orange-vibey)', animation: 'wallPulse 2.4s ease-in-out infinite' }} />
        <span style={{ position: 'absolute', inset: 12, borderRadius: 999, background: 'var(--brand-orange-vibey)', animation: 'wallPulse 2.4s ease-in-out infinite', animationDelay: '0.5s' }} />
        <img src="anna.png" alt="Anna" width="72" height="72" style={{ width: 72, height: 72, borderRadius: 999, objectFit: 'cover', position: 'relative', boxShadow: '0 4px 14px rgba(3,4,13,0.14)' }} />
      </div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, letterSpacing: -0.5, color: H.fg1, lineHeight: 1.2, maxWidth: 280 }}>
        Anna is preparing your first health insight
      </div>
      <div style={{ fontFamily: H.body, fontSize: 14.5, lineHeight: 1.5, color: H.fg2, marginTop: 12, maxWidth: 290 }}>
        She reviews your data twice a week and writes you a personal note. Your wall fills in as the insights land — no action needed.
      </div>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 22, padding: '8px 14px', borderRadius: 999, background: H.bgSecondary }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--success-500)' }} />
        <span style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2 }}>Next insight expected in ~2 days</span>
      </div>
    </div>
  );
}

// ── Error state ──────────────────────────────────────────────────────────────
function WallErrorState({ onRetry }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '80px 34px 40px' }}>
      <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--error-50)', display: 'grid', placeItems: 'center', marginBottom: 22 }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--error-500)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 3 2 20h20Z" /><path d="M12 10v4M12 17v.01" />
        </svg>
      </div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 21, letterSpacing: -0.4, color: H.fg1 }}>Couldn't load your wall</div>
      <div style={{ fontFamily: H.body, fontSize: 14, lineHeight: 1.5, color: H.fg2, marginTop: 10, maxWidth: 280 }}>
        We had trouble reaching Anna just now. Check your connection and try again.
      </div>
      <div style={{ width: 200, marginTop: 22 }}>
        <HPrimaryButton type="outline" onClick={onRetry} icon={
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></svg>
        }>Try again</HPrimaryButton>
      </div>
    </div>
  );
}

// ── Loading footer (infinite scroll) ────────────────────────────────────────
function WallLoadingFooter({ done }) {
  if (done) return (
    <div style={{ textAlign: 'center', padding: '18px 0 6px', fontFamily: H.body, fontSize: 12.5, color: H.fg3 }}>
      You're all caught up
    </div>
  );
  return (
    <div style={{ display: 'flex', justifyContent: 'center', padding: '20px 0 8px' }}>
      <span style={{
        width: 22, height: 22, borderRadius: 999,
        border: '2.5px solid rgba(3,4,13,0.1)', borderTopColor: 'var(--brand-orange-vibey)',
        animation: 'wallSpin 0.8s linear infinite', display: 'inline-block',
      }} />
    </div>
  );
}

Object.assign(window, {
  pillarOf, rgba, WallPillarChip, WallTypeBadge, WallLineChart, WallBadgeArt, WallVoiceArt,
  WallMiniMedia, WallReactionSummary, UnreadDot, WallPostCard, WallPostCardSkeleton,
  WallEmptyState, WallErrorState, WallLoadingFooter, CHART_DATA,
});
