// DIRECTION B — "Mozaik" (Bento / tile-size hierarchy)
// Tile size reflects importance. Featured game = big tile with live board preview.
// Daily & MP = medium. Long tail = small. Status expressed via a dot indicator
// on each tile, not via color-of-whole-tile. Hover lifts + reveals more info.

const { useState: useStateB, useMemo: useMemoB } = React;

function MosaicTile({ game, T, size = 'sm', children, overlay }) {
  const [hover, setHover] = useStateB(false);
  const dimensions = {
    xl: { h: 360, pad: 22, titleSize: 30, descSize: 14, iconScale: 1.4 },
    lg: { h: 220, pad: 18, titleSize: 22, descSize: 12, iconScale: 1.1 },
    md: { h: 170, pad: 14, titleSize: 17, descSize: 11, iconScale: 0.9 },
    sm: { h: 140, pad: 12, titleSize: 14, descSize: 10, iconScale: 0.85 },
    xs: { h: 110, pad: 10, titleSize: 12, descSize: 9, iconScale: 0.75 },
  }[size];

  const done = STATE.today.done.includes(game.id);
  const inProg = STATE.today.inProgress.includes(game.id);

  return (
    <a href="#" onClick={e => e.preventDefault()}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative', overflow: 'hidden',
        borderRadius: 18,
        background: game.accent,
        color: '#fff', textDecoration: 'none',
        height: '100%', minHeight: dimensions.h,
        padding: dimensions.pad,
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
        transition: 'transform 220ms cubic-bezier(.2,.8,.2,1), box-shadow 220ms ease',
        transform: hover ? 'translateY(-4px)' : 'none',
        boxShadow: hover ? `0 24px 40px -16px ${game.accent}cc` : 'none',
      }}>

      {/* Game icon as background art */}
      <img src={`icons/${game.id}.svg`} alt=""
        style={{
          position: 'absolute',
          right: size === 'xl' ? '6%' : '-10%',
          top: '50%',
          transform: `translateY(-50%) scale(${dimensions.iconScale})`,
          width: size === 'xl' ? '45%' : '85%',
          height: size === 'xl' ? '90%' : '90%',
          objectFit: 'contain',
          pointerEvents: 'none',
          transition: 'transform 400ms cubic-bezier(.2,.8,.2,1)',
          ...(hover && {
            transform: `translateY(-52%) scale(${dimensions.iconScale * 1.05})`,
          }),
        }} />

      {/* Gradient scrim */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(to top, ${game.accent} 0%, ${game.accent}cc 28%, ${game.accent}44 55%, transparent 75%)`,
        pointerEvents: 'none',
      }} />

      {/* Top-left dot */}
      {(done || inProg) && (
        <span style={{
          position: 'absolute', top: 12, left: 12, zIndex: 2,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 8px', borderRadius: 999,
          background: 'rgba(255,255,255,0.95)', color: game.accent,
          fontSize: 10, fontWeight: 800, letterSpacing: 0.5,
          textTransform: 'uppercase',
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 999,
            background: done ? '#3a9e5c' : '#c79a1b',
          }} />
          {done ? 'Bitti' : 'Devam'}
        </span>
      )}

      {/* Top-right MP badge */}
      {game.multiplayer && (
        <span style={{
          position: 'absolute', top: 12, right: 12, zIndex: 2,
          padding: '4px 8px', borderRadius: 999,
          background: 'rgba(0,0,0,0.3)', color: '#fff',
          fontSize: 10, fontWeight: 800, letterSpacing: 0.5,
          textTransform: 'uppercase', backdropFilter: 'blur(4px)',
        }}>
          2 Kişilik
        </span>
      )}

      {overlay}

      {/* Bottom text */}
      <div style={{ position: 'relative', zIndex: 1 }}>
        <h3 style={{
          margin: 0, fontWeight: 800,
          fontSize: dimensions.titleSize,
          lineHeight: 1, letterSpacing: -0.5,
          fontFamily: 'Inter, system-ui, sans-serif',
        }}>{game.name}</h3>
        {size !== 'xs' && (
          <p style={{
            margin: '6px 0 0', fontSize: dimensions.descSize,
            opacity: 0.88, lineHeight: 1.35,
            textWrap: 'pretty',
            maxWidth: size === 'xl' ? 320 : 200,
          }}>{size === 'sm' ? '' : game.desc}</p>
        )}
        {children}
      </div>
    </a>
  );
}

// Mini board preview for the featured tile
function MiniKelimelyBoard({ size = 22 }) {
  const rows = [
    { letters: ['k','a','l','e','m'], states: ['a','c','a','a','p'] },
    { letters: ['s','i','l','i','m'], states: ['a','a','a','a','c'] },
    { letters: ['k','e','l','i','m'], states: ['c','c','c','c','c'] },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      {rows.map((r, i) => <TileRow key={i} {...r} size={size} gap={4} />)}
    </div>
  );
}

// "Pro tip" mini card woven into the grid
function TipCard({ T }) {
  return (
    <div style={{
      height: '100%', minHeight: 170,
      background: T.paper, color: T.ink,
      border: `1px dashed ${T.line}`,
      borderRadius: 18, padding: 18,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}>
      <div style={{
        fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase',
        fontWeight: 700, color: T.inkSoft,
      }}>Bugünkü ipucu</div>
      <div style={{
        fontFamily: 'Fraunces, Georgia, serif',
        fontSize: 18, lineHeight: 1.3, letterSpacing: -0.3,
        textWrap: 'balance',
      }}>
        Petek'te pangramı bulmak için <em>önce sesli harflerle</em> dene.
      </div>
      <div style={{ fontSize: 12, color: T.inkSoft }}>
        <StreakBadge n={STATE.user.streak} /> &nbsp;·&nbsp; {STATE.user.name} · Seri günü {STATE.user.streak}
      </div>
    </div>
  );
}

function StreakCard({ T }) {
  const done = STATE.today.done.length;
  const total = 5; // "daily slate"
  const pct = Math.min(done / total, 1);
  return (
    <div style={{
      height: '100%', minHeight: 170,
      background: T.ink, color: T.paper,
      borderRadius: 18, padding: 18,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      position: 'relative', overflow: 'hidden',
    }}>
      <div>
        <div style={{
          fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase',
          fontWeight: 700, opacity: 0.7,
        }}>Günlük seri</div>
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 8,
          fontFamily: 'Fraunces, Georgia, serif',
          fontSize: 56, fontWeight: 700, letterSpacing: -2, lineHeight: 1,
          marginTop: 6,
        }}>
          {STATE.user.streak}
          <span style={{ fontSize: 14, fontWeight: 600, opacity: 0.6, letterSpacing: 0 }}>
            gün üst üste
          </span>
        </div>
      </div>
      <div>
        <div style={{
          fontSize: 11, opacity: 0.6, marginBottom: 6,
        }}>
          Bugün <strong>{done}</strong> / {total} günlük tamamlandı
        </div>
        <div style={{
          height: 6, borderRadius: 999, background: 'rgba(255,255,255,0.15)',
          overflow: 'hidden',
        }}>
          <div style={{
            height: '100%', width: `${pct * 100}%`,
            background: '#E8707F', borderRadius: 999,
            transition: 'width 400ms ease',
          }} />
        </div>
      </div>
    </div>
  );
}

window.MozaikHome = function MozaikHome({ theme }) {
  const T = THEMES[theme];
  const featured = GAMES.find(g => g.id === STATE.today.featuredId);

  // Curated layout. Labels referenced by grid-area.
  // Düello + Eklemce now live in the featured pair above; remove from bento.
  const layout = [
    { id: 'kelimely', area: 'a', size: 'xl' },
    { id: 'petek',    area: 'b', size: 'lg' },
    { id: 'ipucu',    area: 'c', size: 'lg' },
    { id: 'baglac',   area: 'd', size: 'md' },
    { id: 'caprazla', area: 'e', size: 'md' },
    { id: 'karekter', area: 'f', size: 'md' },
    { id: 'tersine',  area: 'g', size: 'md' },
    { id: 'cumlecik', area: 'h', size: 'md' },
    { id: 'gofret',   area: 'i', size: 'md' },
  ];

  const longTail = GAMES.filter(g =>
    !layout.find(l => l.id === g.id)
  );

  return (
    <div style={{
      maxWidth: 1200, margin: '0 auto',
      padding: '28px 24px 80px',
    }}>
      {/* Greeting row */}
      <div style={{
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
        marginBottom: 18, gap: 20, flexWrap: 'wrap',
      }}>
        <div>
          <h1 style={{
            margin: 0,
            fontFamily: 'Fraunces, Georgia, serif',
            fontSize: 'clamp(32px, 4vw, 44px)',
            fontWeight: 600, letterSpacing: -1.2,
            color: T.ink, lineHeight: 1.05,
          }}>
            Selam <span style={{ fontStyle: 'italic' }}>{STATE.user.name}</span>.
            <br/>
            <span style={{ color: T.inkSoft, fontWeight: 400 }}>
              Bugün 3 günlük daha seni bekliyor.
            </span>
          </h1>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          fontSize: 13, color: T.inkSoft,
        }}>
          <span>{STATE.today.date.split(',')[0]}</span>
          <span style={{ width: 1, height: 14, background: T.line }} />
          <span>{STATE.user.totalPlayed} oyun oynandı</span>
        </div>
      </div>

      {/* Featured pair — Playable Eklemce + Live Düello */}
      <MozaikFeaturedPair T={T} />

      {/* THE BENTO */}
      <div style={{
        display: 'grid',
        gap: 14,
        gridTemplateColumns: 'repeat(6, 1fr)',
        gridAutoRows: 'minmax(170px, auto)',
        gridTemplateAreas: `
          "a a a a streak streak"
          "a a a a tip tip"
          "b b c c d d"
          "e e f f g g"
          "h h i i sp sp"
        `,
      }}>
        <div style={{ gridArea: 'a' }}>
          <MosaicTile game={featured} T={T} size="xl"
            overlay={
              <div style={{
                position: 'absolute', top: 22, left: 22, zIndex: 2,
                display: 'flex', flexDirection: 'column', gap: 10,
              }}>
                <span style={{
                  padding: '5px 10px', borderRadius: 6,
                  background: 'rgba(255,255,255,0.2)',
                  color: '#fff', fontSize: 10, fontWeight: 800,
                  letterSpacing: 1.5, textTransform: 'uppercase',
                  backdropFilter: 'blur(6px)', width: 'fit-content',
                }}>Günün Oyunu · No. 1,247</span>
                <div style={{
                  padding: 10, borderRadius: 10,
                  background: 'rgba(255,255,255,0.12)',
                  backdropFilter: 'blur(8px)',
                  width: 'fit-content',
                }}>
                  <MiniKelimelyBoard size={20} />
                </div>
              </div>
            }>
            <div style={{
              marginTop: 14, display: 'flex', gap: 8, flexWrap: 'wrap',
              fontSize: 11, letterSpacing: 0.5,
            }}>
              <Chip>{fmtCount(STATE.playing.kelimely)} oynuyor</Chip>
              <Chip>Ort. 4:12</Chip>
              <Chip>Seri {STATE.streaks.kelimely}</Chip>
            </div>
          </MosaicTile>
        </div>
        <div style={{ gridArea: 'streak' }}><StreakCard T={T} /></div>
        <div style={{ gridArea: 'tip' }}><TipCard T={T} /></div>

        {layout.slice(1).map(l => {
          const g = GAMES.find(x => x.id === l.id);
          return (
            <div key={l.id} style={{ gridArea: l.area }}>
              <MosaicTile game={g} T={T} size={l.size} />
            </div>
          );
        })}
        <div style={{
          gridArea: 'sp',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: T.paper, border: `1px solid ${T.line}`,
          borderRadius: 18, padding: 18,
          color: T.inkSoft, fontSize: 13, textAlign: 'center',
        }}>
          <div>
            <div style={{
              fontFamily: 'Fraunces, Georgia, serif',
              fontSize: 22, color: T.ink, letterSpacing: -0.5,
              marginBottom: 4,
            }}>Daha fazlası →</div>
            Aşağıda 14 oyun daha var
          </div>
        </div>
      </div>

      {/* Long tail — compact row of small tiles */}
      <section style={{ marginTop: 28 }}>
        <div style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          marginBottom: 12,
        }}>
          <h2 style={{
            margin: 0, fontSize: 14, letterSpacing: 1.5,
            textTransform: 'uppercase', fontWeight: 700, color: T.inkSoft,
          }}>Tüm oyunlar</h2>
          <span style={{ fontSize: 12, color: T.inkSoft }}>
            {longTail.length} oyun
          </span>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))',
          gap: 10,
        }}>
          {longTail.map(g => (
            <MosaicTile key={g.id} game={g} T={T} size="xs" />
          ))}
        </div>
      </section>
    </div>
  );
};

function Chip({ children }) {
  return (
    <span style={{
      padding: '5px 10px', borderRadius: 999,
      background: 'rgba(255,255,255,0.18)',
      backdropFilter: 'blur(6px)',
      color: '#fff', fontWeight: 700,
      fontSize: 10, letterSpacing: 0.5, textTransform: 'uppercase',
    }}>{children}</span>
  );
}
