
// Synergy.jsx — Friendship Cards
const { useState } = React;
const { useApp } = window;

function SynergyHearts({ score, max = 3 }) {
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {Array.from({ length: max }).map((_, i) => (
        <span key={i} style={{
          fontSize: 18,
          filter: i < score ? 'none' : 'grayscale(100%) opacity(0.25)',
          transition: 'filter 0.2s',
        }}>❤️</span>
      ))}
    </div>
  );
}

function FriendshipCard({ title, emoji, children, color = '#F2A7C3' }) {
  return (
    <div className="cozy-card" style={{ padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <span style={{ fontSize: 24 }}>{emoji}</span>
        <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18 }}>{title}</span>
      </div>
      {children}
    </div>
  );
}

function ChampPair({ leftId, rightId, label, heartScore }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
      <window.ChampionIcon championId={leftId} size={52} />
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
        <SynergyHearts score={heartScore} />
        <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>{label}</span>
      </div>
      <window.ChampionIcon championId={rightId} size={52} />
    </div>
  );
}

function analyzePair(champData, id1, id2) {
  if (!id1 || !id2) return { score: 0, label: 'Empty slot', text: 'Pick champions to see synergy!' };
  const c1 = champData[id1];
  const c2 = champData[id2];
  if (!c1 || !c2) return { score: 1, label: 'Unknown', text: 'Loading synergy...' };

  const t1 = c1.tags;
  const t2 = c2.tags;
  let score = 1;
  let text = 'These two are just vibing 🌿';
  let label = 'Decent duo';

  // High synergy combos
  if ((t1.includes('Marksman') && t2.includes('Support')) ||
      (t2.includes('Marksman') && t1.includes('Support'))) {
    score = 3; label = 'Bot lane duo'; text = 'Classic bot lane chemistry! 💖';
  } else if ((t1.includes('Tank') && t2.includes('Mage')) ||
             (t2.includes('Tank') && t1.includes('Mage'))) {
    score = 2; label = 'Engage + follow'; text = 'Tank goes in, mage follows up! ⚡';
  } else if ((t1.includes('Fighter') && t2.includes('Support')) ||
             (t2.includes('Fighter') && t1.includes('Support'))) {
    score = 3; label = 'Brawler + healer'; text = 'Unstoppable with heals behind! 💪';
  } else if (t1.includes('Assassin') && t2.includes('Assassin')) {
    score = 2; label = 'Double trouble'; text = 'Two assassins means chaos! 🗡️';
  } else if (t1.some(t => t2.includes(t))) {
    score = 2; label = 'Same class'; text = 'They understand each other! 🤝';
  }

  return { score, label, text };
}

function Synergy() {
  const { players, activeComp, champions, analyzeComp, POSITIONS } = useApp();

  const getChamp = (pos) => window.getSlotChampionId ? window.getSlotChampionId(activeComp[pos]) : (activeComp[pos] && typeof activeComp[pos] === 'object' ? activeComp[pos].championId : activeComp[pos]);
  const analysis = analyzeComp(champions, activeComp);
  const hasComp = POSITIONS.some(pos => Boolean(getChamp(pos)));

  const botDuo = analyzePair(champions, getChamp('ADC'), getChamp('SUPPORT'));
  const jungleTop = analyzePair(champions, getChamp('JUNGLE'), getChamp('TOP'));
  const midJungle = analyzePair(champions, getChamp('MID'), getChamp('JUNGLE'));

  // Overall crew score
  const avgScore = hasComp
    ? Math.round((botDuo.score + jungleTop.score + midJungle.score) / 3)
    : 0;

  const crewTexts = ['', 'Friendly strangers 👋', 'Pretty good pals! 🤝', 'Best friends forever! 💖'];
  const crewEmoji = ['', '😐', '😊', '🥰'];

  const diveQuestions = () => {
    const jungTags = champions[getChamp('JUNGLE')]?.tags || [];
    const topTags = champions[getChamp('TOP')]?.tags || [];
    const canDive = jungTags.includes('Fighter') || jungTags.includes('Tank') || topTags.includes('Fighter');
    return canDive ? 'They LOVE to dive! 🏊' : 'More of a farm-and-scale duo 🌾';
  };

  const roamBuddies = () => {
    const midTags = champions[getChamp('MID')]?.tags || [];
    const jungTags = champions[getChamp('JUNGLE')]?.tags || [];
    const canRoam = midTags.includes('Assassin') || midTags.includes('Fighter') || jungTags.includes('Tank');
    return canRoam ? 'Great roaming duo! 🗺️' : 'Stay in lane, bestie 🏠';
  };

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Synergy Check 🤝
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Friendship letters for your crew — set your comp first!
      </p>

      {!hasComp ? (
        <div className="cozy-card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>💌</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 22, marginBottom: 8 }}>
            No comp set yet!
          </div>
          <div style={{ color: 'var(--text-muted)', fontWeight: 700 }}>
            Head to Team Comp 🍲 and pick your 5 champions first ✨
          </div>
        </div>
      ) : (
        <div className="responsive-two-column">
          {/* Bot Lane Duo */}
          <FriendshipCard title="Bot Lane Duo 💕" emoji="💘">
            <ChampPair
              leftId={getChamp('ADC')}
              rightId={getChamp('SUPPORT')}
              label={botDuo.label}
              heartScore={botDuo.score}
            />
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 10 }}>
              {botDuo.text}
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <window.Tag color="green">Lane style: {botDuo.score >= 3 ? 'Aggressive 💥' : 'Scaling 📈'}</window.Tag>
              {botDuo.score >= 2 && <window.Tag color="green">Strong laning ✅</window.Tag>}
              {botDuo.score < 2 && <window.Tag color="pink">Weak synergy 😅</window.Tag>}
            </div>
          </FriendshipCard>

          {/* Jungle + Top */}
          <FriendshipCard title="Jungle + Top 🌲" emoji="🏊">
            <ChampPair
              leftId={getChamp('JUNGLE')}
              rightId={getChamp('TOP')}
              label={jungleTop.label}
              heartScore={jungleTop.score}
            />
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 10 }}>
              {jungleTop.text}
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <window.Tag color={jungleTop.score >= 2 ? 'green' : 'pink'}>{diveQuestions()}</window.Tag>
            </div>
          </FriendshipCard>

          {/* Mid + Jungle */}
          <FriendshipCard title="Mid + Jungle 🗺️" emoji="🌀">
            <ChampPair
              leftId={getChamp('MID')}
              rightId={getChamp('JUNGLE')}
              label={midJungle.label}
              heartScore={midJungle.score}
            />
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 10 }}>
              {midJungle.text}
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <window.Tag color={midJungle.score >= 2 ? 'green' : 'pink'}>{roamBuddies()}</window.Tag>
            </div>
          </FriendshipCard>

          {/* Team Overall */}
          <FriendshipCard title="Crew Rating 🌟" emoji="🎊">
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 40, marginBottom: 8 }}>{crewEmoji[avgScore]}</div>
              <div style={{ marginBottom: 8 }}>
                <SynergyHearts score={avgScore} />
              </div>
              <div className="fredoka" style={{ fontSize: 22, color: 'var(--accent-orange)', marginBottom: 8 }}>
                {crewTexts[avgScore]}
              </div>
              {analysis && (
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1.5 }}>
                  Overall vibe: <strong>{analysis.vibe}</strong>
                  <br />
                  Win condition: {analysis.winCond} 🌟
                </div>
              )}
            </div>

            {/* All 5 champs in a row */}
            <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 12 }}>
              {POSITIONS.map(pos => (
                <window.ChampionIcon key={pos} championId={getChamp(pos)} size={44} noAnim />
              ))}
            </div>
          </FriendshipCard>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Synergy });
