/* Sims-style mini scene — characters wander, chat bubbles, click to move */

const CHARS = [
  { id: 'c1', name: 'Alex',  color: '#22d3ee', x: 25, y: 55, role: '👨‍💻', lines: ['Shipping v2!', 'Push to prod 🚀', 'Reviewing the PR'] },
  { id: 'c2', name: 'Maya',  color: '#f472b6', x: 45, y: 35, role: '🎨', lines: ['New mockups ✨', 'Need feedback', 'Loving the cyan'] },
  { id: 'c3', name: 'Ethan', color: '#a78bfa', x: 65, y: 60, role: '⛓️', lines: ['Block #482,113', 'Smart contract OK', 'Gas optimized'] },
  { id: 'c4', name: 'Sofia', color: '#fbbf24', x: 75, y: 30, role: '🧠', lines: ['AI agent trained', 'Token economy', 'Mint ready'] },
];

const SimsGame = () => {
  const [chars, setChars] = React.useState(CHARS);
  const [bubbles, setBubbles] = React.useState([]);
  const stageRef = React.useRef(null);
  const bubbleId = React.useRef(0);

  // Random bubbles
  React.useEffect(() => {
    const id = setInterval(() => {
      const ch = chars[Math.floor(Math.random() * chars.length)];
      const line = ch.lines[Math.floor(Math.random() * ch.lines.length)];
      const bid = ++bubbleId.current;
      setBubbles(b => [...b, { id: bid, char: ch.id, text: line }]);
      setTimeout(() => setBubbles(b => b.filter(x => x.id !== bid)), 2400);
    }, 2200);
    return () => clearInterval(id);
  }, [chars]);

  // Auto wander
  React.useEffect(() => {
    const id = setInterval(() => {
      setChars(prev => prev.map(c => ({
        ...c,
        x: Math.max(8, Math.min(88, c.x + (Math.random() - 0.5) * 14)),
        y: Math.max(15, Math.min(80, c.y + (Math.random() - 0.5) * 10)),
      })));
    }, 2600);
    return () => clearInterval(id);
  }, []);

  // Click stage = move nearest character there
  const onStageClick = (e) => {
    if (!stageRef.current) return;
    const rect = stageRef.current.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    // find nearest
    setChars(prev => {
      let bestI = 0, bestD = Infinity;
      prev.forEach((c, i) => {
        const dx = c.x - x, dy = c.y - y;
        const d = dx * dx + dy * dy;
        if (d < bestD) { bestD = d; bestI = i; }
      });
      return prev.map((c, i) => i === bestI ? { ...c, x, y } : c);
    });
  };

  return (
    <div className="ipad-wrap">
      <div className="ipad">
        <div className="ipad-cam"/>
        <div className="ipad-screen">
          <div className="sims-app">
            {/* Status bar */}
            <div className="sims-status">
              <span className="sims-time">9:41</span>
              <span className="sims-app-name">GameHub · Web4 Town</span>
              <span className="sims-status-r">●●● <span className="sims-bat">100%</span></span>
            </div>
            {/* HUD */}
            <div className="sims-hud">
              <div className="sims-hud-item">
                <span className="sims-hud-label">PLAYERS</span>
                <strong>{chars.length}</strong>
              </div>
              <div className="sims-hud-item">
                <span className="sims-hud-label">COINS</span>
                <strong>1,248</strong>
              </div>
              <div className="sims-hud-item">
                <span className="sims-hud-label">QUESTS</span>
                <strong>3 / 5</strong>
              </div>
            </div>

            {/* Stage */}
            <div className="sims-stage" ref={stageRef} onClick={onStageClick}>
              <SimsStageBg/>

              {chars.map(c => {
                const bubble = bubbles.find(b => b.char === c.id);
                return (
                  <div
                    key={c.id}
                    className="sims-char"
                    style={{ left: c.x + '%', top: c.y + '%', '--cc': c.color }}
                  >
                    {bubble && <div className="sims-bubble">{bubble.text}</div>}
                    <div className="sims-char-emoji">{c.role}</div>
                    <div className="sims-char-shadow"/>
                    <div className="sims-char-name">{c.name}</div>
                  </div>
                );
              })}

              <div className="sims-hint">tap anywhere → nearest character moves</div>
            </div>

            {/* Bottom controls */}
            <div className="sims-controls">
              <button className="sims-btn"><span className="sims-btn-ico">🎯</span> Quests</button>
              <button className="sims-btn sims-btn-primary"><span className="sims-btn-ico">⚡</span> Invite</button>
              <button className="sims-btn"><span className="sims-btn-ico">💰</span> Shop</button>
            </div>
          </div>
        </div>
        <div className="ipad-home-indicator"/>
      </div>
    </div>
  );
};

const SimsStageBg = () => (
  <svg className="sims-stage-bg" viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice">
    <defs>
      <linearGradient id="sims-grass" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor="#0d4a52"/>
        <stop offset="1" stopColor="#082f49"/>
      </linearGradient>
      <radialGradient id="sims-glow" cx="0.5" cy="0.4" r="0.6">
        <stop offset="0" stopColor="rgba(34,211,238,0.3)"/>
        <stop offset="1" stopColor="rgba(34,211,238,0)"/>
      </radialGradient>
      <pattern id="sims-iso" width="40" height="22" patternUnits="userSpaceOnUse">
        <path d="M0 11 L20 0 L40 11 L20 22 Z" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="0.6"/>
      </pattern>
    </defs>
    <rect width="600" height="400" fill="url(#sims-grass)"/>
    <rect width="600" height="400" fill="url(#sims-iso)"/>
    <circle cx="300" cy="200" r="220" fill="url(#sims-glow)"/>
    {/* decorative trees / buildings */}
    <g opacity="0.5">
      <rect x="40" y="80" width="36" height="50" rx="3" fill="#1a2230" stroke="#22d3ee" strokeOpacity="0.3"/>
      <rect x="46" y="90" width="6" height="6" fill="#22d3ee" opacity="0.5"/>
      <rect x="58" y="90" width="6" height="6" fill="#22d3ee" opacity="0.5"/>
      <rect x="46" y="105" width="6" height="6" fill="#22d3ee" opacity="0.3"/>
      <rect x="58" y="105" width="6" height="6" fill="#22d3ee" opacity="0.5"/>

      <rect x="520" y="240" width="44" height="60" rx="3" fill="#1a2230" stroke="#5eead4" strokeOpacity="0.3"/>
      <rect x="528" y="252" width="6" height="6" fill="#5eead4" opacity="0.5"/>
      <rect x="540" y="252" width="6" height="6" fill="#5eead4" opacity="0.3"/>
      <rect x="552" y="252" width="6" height="6" fill="#5eead4" opacity="0.5"/>
      <rect x="528" y="266" width="6" height="6" fill="#5eead4" opacity="0.3"/>
      <rect x="540" y="266" width="6" height="6" fill="#5eead4" opacity="0.5"/>
    </g>
    {/* paths */}
    <path d="M0 220 Q300 280 600 200" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="22"/>
  </svg>
);

Object.assign(window, { SimsGame });
