// WorldScreen — full-screen 3D isometric city view
// Shows how user contributions build the virtual world

function WorldScreen({ onClose }) {
  const [phase, setPhase] = React.useState('idle'); // idle | building | done

  // Isometric grid params
  const OX = 190, OY = 248, S = 28; // S = half-cell-width

  // 7 cols × 5 rows city grid: [height, type]
  // type: 's'=standard, 'e'=empty lot, 'c'=contribute target
  const CITY = [
    [[30,'s'],[55,'s'],[70,'s'],[45,'s'],[0,'e'],[25,'s'],[40,'s']],
    [[0,'e'],[65,'s'],[42,'s'],[78,'s'],[32,'s'],[0,'e'],[58,'s']],
    [[52,'s'],[36,'s'],[0,'e'],[62,'s'],[74,'s'],[22,'s'],[0,'e']],
    [[38,'s'],[0,'c'],[56,'s'],[28,'s'],[0,'c'],[64,'s'],[24,'s']],
    [[18,'s'],[68,'s'],[0,'c'],[48,'s'],[34,'s'],[0,'e'],[52,'s']],
  ];

  // Contribution targets: key='col-row' → { height, delay }
  const TARGETS = {
    '1-3': { h: 56, delay: 0 },
    '4-3': { h: 48, delay: 0.22 },
    '2-4': { h: 70, delay: 0.44 },
  };

  function cellXY(col, row) {
    return [OX + col * S - row * S, OY + col * (S / 2) + row * (S / 2)];
  }

  function bldPaths(gx, gy, bh) {
    const h = S / 2; // 14
    const top   = `${gx},${gy-bh-h} ${gx+S},${gy-bh} ${gx},${gy-bh+h} ${gx-S},${gy-bh}`;
    const left  = `${gx-S},${gy-bh} ${gx},${gy-bh+h} ${gx},${gy+h} ${gx-S},${gy}`;
    const right = `${gx},${gy-bh+h} ${gx+S},${gy-bh} ${gx+S},${gy} ${gx},${gy+h}`;
    const floor = `${gx},${gy-h} ${gx+S},${gy} ${gx},${gy+h} ${gx-S},${gy}`;
    return { top, left, right, floor };
  }

  function simulate() {
    if (phase !== 'idle') return;
    setPhase('building');
    setTimeout(() => setPhase('done'), 2800);
  }

  // Build flat sorted cell list (painters algorithm: back → front)
  const cells = [];
  CITY.forEach((row, r) => row.forEach(([height, type], c) => {
    cells.push({ col: c, row: r, height, type });
  }));
  cells.sort((a, b) => (a.col + a.row) - (b.col + b.row));

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: 'oklch(0.11 0.04 175)',
      display: 'flex', flexDirection: 'column',
      animation: 'world-open 0.28s ease-out both',
    }}>

      {/* ── Header ── */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '48px 20px 14px',
      }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'oklch(0.19 0.04 175)',
          border: '1px solid oklch(0.28 0.07 175)',
          color: 'oklch(0.78 0.10 175)',
          cursor: 'pointer', fontSize: 16,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>←</button>
        <div>
          <div style={{
            fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 700,
            color: 'oklch(0.93 0.06 175)', letterSpacing: '-0.01em',
          }}>Virtual World</div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10,
            color: 'oklch(0.55 0.11 175)', letterSpacing: '0.08em',
          }}>DAIKANYAMA · 47% MAPPED</div>
        </div>
        <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 20, fontWeight: 800,
            color: 'oklch(0.80 0.18 175)',
          }}>{phase === 'done' ? 130 : 127}</div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 9,
            color: 'oklch(0.48 0.10 175)', letterSpacing: '0.06em',
          }}>BLOCKS BUILT</div>
        </div>
      </div>

      {/* ── 3D Scene ── */}
      <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
        <svg viewBox="0 0 390 460" width="390" height="460" style={{ display: 'block' }}>

          {/* Ambient floor haze */}
          <defs>
            <radialGradient id="floorGlow" cx="50%" cy="60%" r="55%">
              <stop offset="0%" stopColor="oklch(0.22 0.07 175)" stopOpacity="0.5"/>
              <stop offset="100%" stopColor="oklch(0.11 0.04 175)" stopOpacity="0"/>
            </radialGradient>
          </defs>
          <rect width="390" height="460" fill="url(#floorGlow)"/>

          {/* Ground grid cells */}
          {cells.map(({ col, row }) => {
            const [gx, gy] = cellXY(col, row);
            const { floor } = bldPaths(gx, gy, 0);
            return (
              <polygon key={`f${col}-${row}`} points={floor}
                fill="none" stroke="oklch(0.21 0.06 175)" strokeWidth="0.6"/>
            );
          })}

          {/* Buildings */}
          {cells.map(({ col, row, height, type }) => {
            const key = `${col}-${row}`;
            const [gx, gy] = cellXY(col, row);
            const tgt = TARGETS[key];
            const isContrib = type === 'c';
            const bh = isContrib ? (tgt ? tgt.h : 52) : height;
            const contributed = isContrib && phase !== 'idle';
            const animating   = isContrib && phase === 'building';
            const delay = tgt ? tgt.delay : 0;

            if (type === 'e') return null;

            const { top, left, right } = bldPaths(gx, gy, bh);

            // Pre-contribute wireframe ghost
            if (isContrib && !contributed) return (
              <g key={key} opacity={0.32}>
                <polygon points={top}   fill="none" stroke="oklch(0.70 0.16 175)" strokeWidth="0.9" strokeDasharray="3 2"/>
                <polygon points={left}  fill="none" stroke="oklch(0.70 0.16 175)" strokeWidth="0.9" strokeDasharray="3 2"/>
                <polygon points={right} fill="none" stroke="oklch(0.70 0.16 175)" strokeWidth="0.9" strokeDasharray="3 2"/>
              </g>
            );

            // Animating / completed contribution — bright teal
            if (isContrib) return (
              <g key={key} style={animating ? {
                animation: `building-grow 0.55s cubic-bezier(0.34, 1.56, 0.64, 1) ${delay}s both`,
                transformBox: 'fill-box',
                transformOrigin: '50% 100%',
              } : {}}>
                <polygon points={top}   fill="oklch(0.83 0.20 175)"/>
                <polygon points={left}  fill="oklch(0.61 0.15 175)"/>
                <polygon points={right} fill="oklch(0.47 0.11 175)"/>
                {/* Highlight shimmer on top */}
                <polygon points={top} fill="white" opacity={animating ? 0.28 : 0.14}/>
              </g>
            );

            // Standard building
            return (
              <g key={key}>
                <polygon points={top}   fill="oklch(0.66 0.10 175)"/>
                <polygon points={left}  fill="oklch(0.49 0.08 175)"/>
                <polygon points={right} fill="oklch(0.37 0.06 175)"/>
              </g>
            );
          })}
        </svg>
      </div>

      {/* ── Bottom bar ── */}
      <div style={{
        padding: '12px 20px 36px',
        background: 'linear-gradient(transparent, oklch(0.09 0.04 175) 40%)',
      }}>
        {phase === 'done' && (
          <div style={{
            background: 'oklch(0.17 0.06 175)',
            border: '1px solid oklch(0.48 0.14 175)',
            borderRadius: 12, padding: '11px 16px',
            display: 'flex', alignItems: 'center', gap: 12,
            marginBottom: 10,
            animation: 'world-open 0.25s ease-out both',
          }}>
            <div style={{
              width: 34, height: 34, borderRadius: 9,
              background: 'oklch(0.80 0.20 175)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 15, color: '#fff',
            }}>✓</div>
            <div>
              <div style={{
                fontSize: 14, fontWeight: 700,
                color: 'oklch(0.93 0.08 175)',
              }}>3 blocks built</div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11,
                color: 'oklch(0.58 0.12 175)', marginTop: 2,
              }}>Daikanyama · 50% complete</div>
            </div>
          </div>
        )}
        <button onClick={simulate} disabled={phase !== 'idle'} style={{
          width: '100%', height: 48, borderRadius: 12,
          background: phase !== 'idle' ? 'oklch(0.19 0.04 175)' : 'oklch(0.64 0.16 175)',
          border: `1px solid ${phase !== 'idle' ? 'oklch(0.26 0.06 175)' : 'oklch(0.76 0.18 175)'}`,
          cursor: phase !== 'idle' ? 'default' : 'pointer',
          color: phase !== 'idle' ? 'oklch(0.42 0.08 175)' : '#fff',
          fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
          transition: 'all 0.2s',
          boxShadow: phase === 'idle' ? '0 2px 16px oklch(0.64 0.16 175 / 0.4)' : 'none',
        }}>
          {phase === 'idle'     && '▣  Simulate contribution'}
          {phase === 'building' && '⬡  Building world…'}
          {phase === 'done'     && '✓  Contribution added'}
        </button>
      </div>
    </div>
  );
}

window.WorldScreen = WorldScreen;
