const PostCard = ({ post, palette, index }) => {
  const d = post.publish_date ? new Date(post.publish_date * 1000) : null;
  const dateStr = d
    ? d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).toUpperCase()
    : '';
  const tilts = [-0.6, 0.4, -0.3];
  const tilt = tilts[index % tilts.length];
  const [hover, setHover] = React.useState(false);

  return (
    <a
      href={post.web_url}
      target="_blank"
      rel="noopener noreferrer"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex',
        flexDirection: 'column',
        textDecoration: 'none',
        color: 'inherit',
        background: 'var(--paper)',
        border: '2px solid var(--ink)',
        borderRadius: 6,
        boxShadow: hover ? '7px 7px 0 var(--ink)' : '5px 5px 0 var(--ink)',
        transform: hover
          ? `rotate(${tilt}deg) translate(-2px, -2px)`
          : `rotate(${tilt}deg)`,
        overflow: 'hidden',
        transition: 'transform 180ms ease, box-shadow 180ms ease',
      }}
    >
      <div
        style={{
          aspectRatio: '16 / 9',
          background: post.thumbnail_url
            ? `center/cover url(${post.thumbnail_url})`
            : `linear-gradient(135deg, ${palette.sky}, ${palette.skyDeep})`,
          borderBottom: '2px solid var(--ink)',
        }}
      />
      <div style={{ padding: '20px 22px 22px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        {dateStr && (
          <div
            className="mono"
            style={{
              fontSize: 11,
              letterSpacing: '0.22em',
              textTransform: 'uppercase',
              color: 'var(--ink-soft)',
              marginBottom: 10,
            }}
          >
            {dateStr}
          </div>
        )}
        <h3
          style={{
            fontFamily: "'Instrument Serif', Georgia, serif",
            fontWeight: 500,
            fontSize: 26,
            lineHeight: 1.15,
            margin: 0,
            color: 'var(--ink)',
          }}
        >
          {post.title}
        </h3>
        {post.subtitle && (
          <p
            style={{
              fontSize: 15,
              lineHeight: 1.5,
              marginTop: 10,
              marginBottom: 0,
              color: 'var(--ink-soft)',
              flex: 1,
            }}
          >
            {post.subtitle}
          </p>
        )}
        <div
          className="mono"
          style={{
            marginTop: 18,
            fontSize: 11,
            fontWeight: 700,
            letterSpacing: '0.18em',
            textTransform: 'uppercase',
            color: palette.accent,
          }}
        >
          Read issue →
        </div>
      </div>
    </a>
  );
};

const LatestPosts = ({ tweaks }) => {
  const p = getPalette(tweaks);
  const [posts, setPosts] = React.useState(null);
  const [failed, setFailed] = React.useState(false);

  React.useEffect(() => {
    let alive = true;
    fetch('/api/posts')
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('load failed'))))
      .then((d) => { if (alive) setPosts(Array.isArray(d.posts) ? d.posts : []); })
      .catch(() => { if (alive) setFailed(true); });
    return () => { alive = false; };
  }, []);

  if (failed) return null;
  if (!posts || posts.length === 0) return null;

  return (
    <section
      style={{
        position: 'relative',
        background: 'var(--paper)',
        color: 'var(--ink)',
        padding: 'clamp(56px, 9vw, 104px) clamp(20px, 5vw, 64px)',
        borderTop: '2px solid var(--ink)',
      }}
    >
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'baseline',
            justifyContent: 'space-between',
            gap: 16,
            flexWrap: 'wrap',
            marginBottom: 40,
          }}
        >
          <div
            className="mono"
            style={{
              fontSize: 12,
              fontWeight: 700,
              letterSpacing: '0.22em',
              textTransform: 'uppercase',
              color: 'var(--ink)',
              padding: '6px 14px',
              border: '2px solid var(--ink)',
              borderRadius: 999,
              boxShadow: '3px 3px 0 var(--ink)',
              transform: 'rotate(-0.8deg)',
              background: p.sky,
              whiteSpace: 'nowrap',
            }}
          >
            ◆ Latest Issues
          </div>
          <div
            className="mono"
            style={{
              fontSize: 11,
              letterSpacing: '0.2em',
              textTransform: 'uppercase',
              color: 'var(--ink-soft)',
            }}
          >
            Three most recent · Five minute reads
          </div>
        </div>

        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
            gap: 28,
          }}
        >
          {posts.map((post, i) => (
            <PostCard key={post.id} post={post} palette={p} index={i} />
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { LatestPosts, PostCard });
