// Savvie · reusable components
// Logo, Badge, DecayTimeline, ItemRow, ItemCard

const { useState, useEffect, useRef } = React;

// =================== LOGO ====================================
// Wordmark: "savv" + dotless "ı" + "e", with the orange liquid blob
// sitting above the dotless i where the dot would be.
function Logo({ size = 32 }) {
  const blobSize = Math.max(8, size * 0.22);
  return (
    <span
      className="sv-logo"
      style={{ fontSize: size, position: 'relative', display: 'inline-flex', alignItems: 'baseline' }}
    >
      <span>savv</span>
      <span style={{ position: 'relative', display: 'inline-block', lineHeight: 1 }}>
        ı
        <span
          className="sv-logo-blob"
          style={{
            position: 'absolute',
            width: blobSize,
            height: blobSize,
            left: '50%',
            top: `-${blobSize * 0.55}px`,
            transform: 'translateX(-50%) rotate(-12deg)',
            margin: 0,
          }}
        />
      </span>
      <span>e</span>
    </span>
  );
}

// =================== BLOB ====================================
function Blob({ size = 32, color = 'orange', rotate = -12, style = {} }) {
  const bg = {
    orange: 'var(--vz-orange)',
    cobalt: 'var(--vz-cobalt)',
    lime:   'var(--vz-lime)',
    pink:   'var(--vz-pink)',
    ink:    'var(--vz-ink)',
  }[color] || color;
  return (
    <span style={{
      display: 'inline-block',
      width: size, height: size,
      background: bg,
      border: '1px solid var(--vz-ink)',
      borderRadius: '62% 38% 55% 45% / 50% 60% 40% 50%',
      transform: `rotate(${rotate}deg)`,
      ...style,
    }} />
  );
}

// =================== AGE CHIP ===============================
// Neutral age display. No "stale/fresh/aging" labels in the UI —
// the decay state still drives the dot color subtly, but the
// user sees just "47d" instead of "STALE 47d".
function DecayBadge({ decay, age, withDays = true }) {
  return (
    <span className={`sv-age-chip ${decay}`}>
      <span className="dot"></span>
      <span>{age}</span>
    </span>
  );
}

// =================== ITEM ROW (list view) ====================
function ItemRow({ item, compact, onClick, onArchive, onCategoryChange }) {
  const [dragging, setDragging] = useState(false);
  return (
    <button
      className={`sv-item-row ${compact ? 'compact' : ''} ${dragging ? 'is-dragging' : ''}`}
      data-screen-label={`row · ${item.title}`}
      onClick={() => onClick(item)}
      draggable
      onDragStart={(e) => {
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', item.id);
        e.dataTransfer.setData('application/x-savvie-item', item.id);
        setDragging(true);
      }}
      onDragEnd={() => setDragging(false)}
    >
      <span className="sv-row-handle" aria-hidden="true">⋮⋮</span>
      <div className={`sv-item-cat ${item.thumb ? 'has-thumb' : ''}`}>
        {item.thumb
          ? <img src={item.thumb} alt="" className="thumb" />
          : <span style={{ color: 'var(--vz-cobalt)' }}>{item.cat.emoji}</span>}
        <span className="decay-ring"></span>
      </div>

      <div className="sv-item-body">
        <span className="sv-item-title">{item.title}</span>
        <div className="sv-item-meta">
          <span className="platform">{item.source}</span>
          <span className="dot">·</span>
          <span className="category">{item.cat.label}</span>
        </div>
        {!compact && (
          <div className="sv-item-tags">
            {item.tags.slice(0, 3).map(t => (
              <span key={t} className="sv-tag">{t}</span>
            ))}
          </div>
        )}
      </div>

      <div className="sv-item-actions">
        <div className="sv-action-buttons">
          <span
            className="sv-btn execute"
            onClick={(e) => { e.stopPropagation(); onClick(item); }}
            role="button"
          >action</span>
          <span
            className="sv-btn done"
            onClick={(e) => { e.stopPropagation(); onArchive(item); }}
            role="button"
          >done</span>
        </div>
      </div>
    </button>
  );
}

// =================== ITEM CARD (grid view) ===================
function ItemCard({ item, onClick }) {
  return (
    <button
      className={`sv-card`}
      data-screen-label={`card · ${item.title}`}
      onClick={() => onClick(item)}
    >
      <div className="sv-card-media">
        {item.thumb
          ? <img src={item.thumb} alt={item.title} />
          : <div className="placeholder" style={{ background: 'var(--vz-cream-deep)' }}>
              <span style={{ color: 'var(--vz-cobalt)', fontFamily: 'var(--vz-display)', fontSize: 56, fontStyle: 'italic' }}>
                {item.cat.emoji}
              </span>
            </div>}
        <div className="corner-badge">
          <DecayBadge decay={item.decay} age={item.age} withDays={false} />
        </div>
      </div>
      <div className="sv-card-body">
        <h3 className="sv-card-title">{item.title}</h3>
        <div className="sv-card-meta">
          <span className="cat">{item.cat.label}</span>
          <span>·</span>
          <span>{item.age}</span>
          <span>·</span>
          <span>{item.source}</span>
        </div>
      </div>
    </button>
  );
}

// =================== DECAY TIMELINE ==========================
// A 56-day strip showing day-by-day saves. Each bar's height = count for that day.
function DecayTimeline({ items, annotation = true }) {
  const days = 56;
  const today = new Date('2026-05-13T12:00:00Z');
  // Build day buckets
  const buckets = Array(days).fill(0).map((_, i) => ({
    daysAgo: days - 1 - i,
    count: 0,
    state: null,
  }));
  items.forEach(item => {
    const idx = days - 1 - item.daysOld;
    if (idx >= 0 && idx < days) {
      buckets[idx].count++;
      // state based on TODAY's perspective
      buckets[idx].state = item.decay;
    }
  });
  const maxCount = Math.max(1, ...buckets.map(b => b.count));

  return (
    <div className="sv-decay-timeline">
      <div className="sv-decay-timeline-head">
        <h3>your last <em>8 weeks</em> of saves.</h3>
        <span className="meta">tap any day to scroll · today on the right →</span>
      </div>
      <div className="sv-decay-track" style={{ paddingBottom: 24 }}>
        {buckets.map((b, i) => (
          <div
            key={i}
            className={`day ${b.state || ''}`}
            style={{
              height: `${6 + (b.count / maxCount) * 46}px`,
              opacity: b.count === 0 ? 0.35 : 1,
            }}
            title={b.count ? `${b.count} save${b.count > 1 ? 's' : ''} · ${b.daysAgo}d ago` : ''}
          />
        ))}
        <span className="axis left">8 weeks ago</span>
        <span className="axis middle">4 weeks ago</span>
        <span className="axis right">today</span>
      </div>
      {annotation && (
        <span
          className="sv-decay-annotation"
          style={{ left: '6%', top: 22 }}
        >
          ← ready to revisit.
        </span>
      )}
    </div>
  );
}

// =================== EXPORT ==================================
Object.assign(window, {
  Logo, Blob, DecayBadge, ItemRow, ItemCard, DecayTimeline,
});
