
// TeamComp.jsx — Recipe builder
const { useState, useMemo, useRef, useEffect } = React;
const { useApp } = window;

const CLASS_FILTER_TAGS = ['All', 'Tank', 'Fighter', 'Mage', 'Assassin', 'Marksman', 'Support'];
const CLASS_FILTER_EMOJIS = { All:'🌟', Tank:'🛡️', Fighter:'💪', Mage:'🔮', Assassin:'🗡️', Marksman:'🏹', Support:'💛' };

function ChampionPickerPopover({ pool, champions, playerName, roleLabel, currentSlot, onImmediateChange, onCommit, onClose }) {
  const [search, setSearch] = useState('');
  const [filterTag, setFilterTag] = useState('All');
  const initialStarter = window.getSlotChampionId ? window.getSlotChampionId(currentSlot) : (currentSlot?.championId || null);
  const initialAlternates = window.getSlotAlternates ? window.getSlotAlternates(currentSlot) : (currentSlot?.alternates || []);
  const [starter, setStarter] = useState(initialStarter);
  const [alternates, setAlternates] = useState(initialAlternates);
  const ref = useRef(null);

  const selectionRef = useRef({ championId: initialStarter, alternates: initialAlternates });

  useEffect(() => {
    const champId = window.getSlotChampionId ? window.getSlotChampionId(currentSlot) : (currentSlot?.championId || null);
    const alts = window.getSlotAlternates ? window.getSlotAlternates(currentSlot) : (currentSlot?.alternates || []);
    setStarter(champId);
    setAlternates(alts);
    selectionRef.current = { championId: champId, alternates: alts };
  }, [currentSlot]);

  useEffect(() => {
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) {
        if (onCommit) onCommit(selectionRef.current);
        onClose();
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [onCommit, onClose]);

  const results = useMemo(() => {
    return pool
      .map(entry => ({ entry, champ: champions[entry.championId] }))
      .filter(({ champ }) => champ)
      .filter(({ champ }) => filterTag === 'All' || champ.tags.includes(filterTag))
      .filter(({ champ }) => (window.matchesChampionSearch ? window.matchesChampionSearch(champ, search) : (!search || champ.name.toLowerCase().includes(search.toLowerCase()))))
      .sort((a, b) => b.entry.comfort - a.entry.comfort || a.champ.name.localeCompare(b.champ.name));
  }, [pool, champions, filterTag, search]);

  const handleToggleChamp = (champId) => {
    const currentStarter = selectionRef.current.championId;
    const currentAlts = selectionRef.current.alternates;

    let nextStarter = currentStarter;
    let nextAlts = [...currentAlts];

    if (currentStarter === champId) {
      // Tapping starter removes it; promote first alternate if any
      const [promoted, ...rest] = currentAlts;
      nextStarter = promoted || null;
      nextAlts = rest;
    } else if (currentAlts.includes(champId)) {
      // Tapping alternate removes it
      nextAlts = currentAlts.filter(id => id !== champId);
    } else if (!currentStarter) {
      // Empty role: tapping sets starter immediately
      nextStarter = champId;
    } else {
      // Starter set: add as alternate up to cap of 4
      if (currentAlts.length < 4) {
        nextAlts = [...currentAlts, champId];
      }
    }

    selectionRef.current = { championId: nextStarter, alternates: nextAlts };
    setStarter(nextStarter);
    setAlternates(nextAlts);
    if (onImmediateChange) onImmediateChange({ championId: nextStarter, alternates: nextAlts });
  };

  return (
    <div ref={ref} className="cozy-card" style={{
      position: 'absolute', top: '100%', left: '50%', transform: 'translateX(-50%)',
      marginTop: 8, width: 275, padding: 12, zIndex: 50, background: 'var(--surface-modal)',
      boxShadow: '0 8px 24px var(--border-default)', textAlign: 'left',
    }}>
      <input
        autoFocus
        value={search}
        onChange={e => setSearch(e.target.value)}
        placeholder="Search champions..."
        style={{
          width: '100%', padding: '7px 12px', border: '2px solid var(--border-default)', borderRadius: 12,
          fontFamily: 'Nunito', fontSize: 13, fontWeight: 600, background: 'var(--surface-nested)',
          color: 'var(--text-primary)', outline: 'none', boxSizing: 'border-box', marginBottom: 8,
        }}
      />
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 6 }}>
        {CLASS_FILTER_TAGS.map(tag => (
          <button key={tag} onClick={() => setFilterTag(tag)} className="cozy-btn" style={{
            background: filterTag === tag ? 'var(--accent-orange)' : 'var(--surface-nested)',
            color: filterTag === tag ? 'white' : 'var(--text-primary)',
            border: '2px solid var(--border-default)', borderRadius: 16,
            padding: '2px 8px', fontSize: 10, fontWeight: 800,
            fontFamily: 'Nunito', cursor: 'pointer',
          }}>
            {CLASS_FILTER_EMOJIS[tag]}
          </button>
        ))}
      </div>

      <div style={{
        fontSize: 10.5, fontWeight: 700, color: 'var(--text-muted)',
        marginBottom: 8, textAlign: 'center', lineHeight: 1.3,
      }}>
        Tap to add alternates — first pick is the starter
      </div>

      {pool.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '20px 8px', color: 'var(--text-muted)', fontSize: 12, fontWeight: 700 }}>
          {playerName} hasn't built their {roleLabel} pool yet 🌱
        </div>
      ) : results.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '20px 8px', color: 'var(--text-muted)', fontSize: 12, fontWeight: 700 }}>
          No champions match — try a different filter 🌿
        </div>
      ) : (
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(52px, 1fr))',
          gap: 6, maxHeight: 220, overflowY: 'auto', paddingRight: 2,
        }}>
          {results.map(({ entry, champ }) => {
            const isStarter = starter === entry.championId;
            const altIndex = alternates.indexOf(entry.championId);
            const isAlt = altIndex !== -1;

            return (
              <div
                key={entry.championId}
                onClick={() => handleToggleChamp(entry.championId)}
                title={champ.name}
                className="champion-sticker"
                style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  gap: 2, cursor: 'pointer', position: 'relative',
                  padding: 2, borderRadius: 12,
                  border: isStarter ? '2px solid #E5A272' : (isAlt ? '2px dashed var(--accent-orange)' : '2px solid transparent'),
                  background: isStarter ? 'rgba(229, 162, 114, 0.2)' : (isAlt ? 'rgba(196, 132, 90, 0.1)' : 'transparent'),
                  transition: 'all 0.15s ease',
                }}
              >
                <div style={{ position: 'relative' }}>
                  <window.ChampionIcon
                    championId={entry.championId}
                    size={44}
                    noAnim
                    style={isStarter ? {
                      boxShadow: '0 0 0 2px #F7DFA0, 0 2px 6px rgba(229, 162, 114, 0.5)',
                      borderRadius: 10,
                    } : (isAlt ? {
                      boxShadow: '0 0 0 1.5px var(--accent-orange)',
                      borderRadius: 10,
                    } : {})}
                  />
                  {isStarter && (
                    <div style={{
                      position: 'absolute', top: -4, right: -4,
                      background: '#F7DFA0', color: 'var(--text-on-light)', border: '1px solid #E5A272',
                      borderRadius: 8, fontSize: 8, fontWeight: 900, padding: '0 3px',
                      boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
                    }}>
                      ★
                    </div>
                  )}
                  {isAlt && (
                    <div style={{
                      position: 'absolute', top: -4, right: -4,
                      background: 'var(--accent-orange)', color: 'white',
                      borderRadius: 8, fontSize: 8, fontWeight: 900, padding: '0 3px',
                      boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
                    }}>
                      +{altIndex + 1}
                    </div>
                  )}
                  <div style={{
                    position: 'absolute', bottom: -3, left: '50%', transform: 'translateX(-50%)',
                    background: 'var(--surface-card)', border: '1px solid var(--border-default)', borderRadius: 8,
                    padding: '0 2px', lineHeight: 1,
                  }}>
                    <window.StarRating value={entry.comfort} size={7} />
                  </div>
                </div>
                <span style={{
                  fontSize: 9, fontWeight: isStarter || isAlt ? 800 : 700,
                  color: isStarter ? 'var(--accent-orange)' : 'var(--text-primary)',
                  textAlign: 'center', whiteSpace: 'nowrap', overflow: 'hidden',
                  textOverflow: 'ellipsis', maxWidth: 56, marginTop: 3,
                }}>
                  {champ.name}
                </span>
              </div>
            );
          })}
        </div>
      )}

      {/* Footer bar with Done button */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginTop: 10, paddingTop: 8, borderTop: '1.5px solid var(--border-default)',
      }}>
        <span style={{
          fontSize: 11, fontWeight: 700, color: 'var(--text-primary)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 175,
        }}>
          {starter ? (
            <>
              <strong>{champions[starter]?.name || starter}</strong>
              {alternates.length > 0 && (
                <span style={{ color: 'var(--text-muted)', fontSize: 10, marginLeft: 4 }}>
                  +{alternates.length} alt{alternates.length > 1 ? 's' : ''}
                </span>
              )}
            </>
          ) : (
            <span style={{ color: 'var(--text-muted)' }}>None selected</span>
          )}
        </span>
        <button
          onClick={() => {
            if (onCommit) onCommit(selectionRef.current);
            onClose();
          }}
          className="cozy-btn"
          style={{
            background: 'var(--accent-orange)', color: 'white', border: 'none',
            borderRadius: 12, padding: '4px 12px', fontSize: 11, fontWeight: 800,
            fontFamily: 'Nunito', cursor: 'pointer',
          }}
        >
          Done ✨
        </button>
      </div>
    </div>
  );
}

function TeamComp() {
  const {
    players, activeComp, setActiveComp, champions, championsLoading, getEffectivePlayerPool,
    analyzeComp, saveComp, showToast, POSITIONS, POSITION_EMOJIS,
    activeCompNotes, addActiveCompNote, editActiveCompNote, deleteActiveCompNote,
  } = useApp();

  const [compName, setCompName] = useState('');
  const [openPicker, setOpenPicker] = useState(null);

  const normalizeSlot = (posVal) => {
    return window.normalizeRoleSlot ? window.normalizeRoleSlot(posVal) : { championId: posVal || null, alternates: [] };
  };

  const handleSlotChange = (pos, slotData) => {
    const normalized = window.normalizeRoleSlot
      ? window.normalizeRoleSlot(slotData)
      : (typeof slotData === 'object' && slotData !== null
          ? { championId: slotData.championId || slotData.starter || null, alternates: slotData.alternates || [] }
          : { championId: slotData || null, alternates: [] });
    setActiveComp({ ...activeComp, [pos]: normalized });
  };

  const handleSave = () => {
    const hasAny = POSITIONS.some(pos => {
      const champId = window.getSlotChampionId ? window.getSlotChampionId(activeComp[pos]) : activeComp[pos];
      return Boolean(champId);
    });
    if (!hasAny) { showToast('Add some champions first! 🌱'); return; }

    const formattedRoles = {};
    POSITIONS.forEach(pos => {
      formattedRoles[pos] = normalizeSlot(activeComp[pos]);
    });

    saveComp({
      ...formattedRoles,
      name: compName || analysis?.vibe || 'Cozy Comp',
      notes: activeCompNotes,
    });
    showToast('Recipe saved! 📦✨');
    setCompName('');
  };

  if (championsLoading) return <window.LoadingSpinner />;

  const analysis = analyzeComp(champions, activeComp);
  const hasComp = POSITIONS.some(pos => {
    const champId = window.getSlotChampionId ? window.getSlotChampionId(activeComp[pos]) : activeComp[pos];
    return Boolean(champId);
  });

  const statColors = {
    cc: '#C5B4E3', frontline: '#7CBF8E', engage: '#F7DFA0',
    lateGame: '#F2A7C3', botSafety: '#AED6F1',
  };

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        What are we cooking? 🍲
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Pick one champion per role to build your team recipe
      </p>

      {/* 5 ingredient bubbles */}
      <div className="cozy-card" style={{ padding: 24, marginBottom: 20 }}>
        <div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
          {POSITIONS.map(pos => {
            const player = players.find(p => p.position === pos);
            const rawPool = player && getEffectivePlayerPool ? getEffectivePlayerPool(player) : (player?.pool || []);
            const posPool = rawPool.filter(c => !c.position || c.position.toUpperCase() === pos.toUpperCase());
            const slotData = normalizeSlot(activeComp[pos]);
            const selected = slotData.championId;
            const alternates = slotData.alternates;

            const champName = selected ? (champions[selected]?.name || selected) : null;

            return (
              <div key={pos} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, position: 'relative' }}>
                {/* Bubble Container */}
                <div style={{ position: 'relative' }}>
                  <div
                    onClick={() => setOpenPicker(openPicker === pos ? null : pos)}
                    style={{
                      width: 80, height: 80, borderRadius: '50%',
                      border: `3px solid ${selected ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
                      background: selected ? 'var(--surface-card)' : 'var(--surface-nested)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      boxShadow: selected ? '0 4px 16px var(--border-default)' : 'none',
                      transition: 'all 0.3s', overflow: 'hidden', cursor: 'pointer',
                    }}>
                    {selected ? (
                      <window.ChampionIcon championId={selected} size={76} noAnim style={{ borderRadius: '50%' }} />
                    ) : (
                      <span style={{ fontSize: 28 }}>{POSITION_EMOJIS[pos]}</span>
                    )}
                  </div>

                  {/* Remove starter "x" affordance */}
                  {selected && (
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        const nextSlot = window.removeStarterFromSlot
                          ? window.removeStarterFromSlot(activeComp[pos])
                          : (alternates.length > 0
                              ? { championId: alternates[0], alternates: alternates.slice(1) }
                              : { championId: null, alternates: [] });
                        handleSlotChange(pos, nextSlot);
                      }}
                      title="Remove starter"
                      style={{
                        position: 'absolute', top: 0, right: 0, width: 20, height: 20,
                        borderRadius: '50%', background: 'var(--accent-orange)', color: 'white',
                        fontSize: 12, fontWeight: 900, display: 'flex', alignItems: 'center',
                        justifyContent: 'center', cursor: 'pointer', lineHeight: 1,
                        boxShadow: '0 2px 5px rgba(0,0,0,0.25)', border: '2px solid var(--surface-card)',
                        zIndex: 10,
                      }}
                    >
                      ×
                    </div>
                  )}
                </div>

                {/* Inline alternate chips beneath main portrait */}
                {alternates.length > 0 && (
                  <div style={{ display: 'flex', gap: 4, alignItems: 'center', justifyContent: 'center', minHeight: 22, marginTop: -2 }}>
                    {alternates.map(altId => (
                      <div
                        key={altId}
                        onClick={(e) => {
                          e.stopPropagation();
                          const nextSlot = window.promoteAlternateToStarter
                            ? window.promoteAlternateToStarter(activeComp[pos], altId)
                            : { championId: altId, alternates };
                          handleSlotChange(pos, nextSlot);
                        }}
                        style={{ position: 'relative', width: 22, height: 22, cursor: 'pointer' }}
                        title={`Promote ${champions[altId]?.name || altId} to starter`}
                        className="champion-sticker"
                      >
                        <window.ChampionIcon championId={altId} size={22} noAnim style={{ borderRadius: '50%' }} />
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                            const nextAlts = alternates.filter(id => id !== altId);
                            handleSlotChange(pos, { championId: selected, alternates: nextAlts });
                          }}
                          title={`Remove alternate ${champions[altId]?.name || altId}`}
                          style={{
                            position: 'absolute', top: -3, right: -3, width: 11, height: 11,
                            borderRadius: '50%', background: 'var(--accent-orange)', color: 'white',
                            fontSize: 8, fontWeight: 900, display: 'flex', alignItems: 'center',
                            justifyContent: 'center', cursor: 'pointer', lineHeight: 1,
                            boxShadow: '0 1px 2px rgba(0,0,0,0.3)',
                          }}
                        >
                          ×
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* Label */}
                <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--accent-orange)' }}>{pos}</span>
                {player && <span style={{ fontSize: 10, color: 'var(--text-primary)', fontWeight: 700 }}>{player.name}</span>}

                {/* Slot trigger */}
                <button
                  onClick={() => setOpenPicker(openPicker === pos ? null : pos)}
                  className="cozy-btn"
                  style={{
                    border: '2px solid var(--border-default)', borderRadius: 12,
                    padding: '4px 10px', fontSize: 12, fontWeight: 700,
                    fontFamily: 'Nunito', color: 'var(--text-primary)',
                    background: 'var(--surface-nested)', cursor: 'pointer',
                    maxWidth: 120, outline: 'none',
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  }}
                >
                  {champName ? (
                    alternates.length > 0 ? `${champName} (+${alternates.length})` : champName
                  ) : 'Pick champion…'}
                </button>

                {openPicker === pos && (
                  <ChampionPickerPopover
                    pool={posPool}
                    champions={champions}
                    playerName={player?.name || pos}
                    roleLabel={pos}
                    currentSlot={slotData}
                    onImmediateChange={(slot) => handleSlotChange(pos, slot)}
                    onCommit={(slot) => handleSlotChange(pos, slot)}
                    onClose={() => setOpenPicker(null)}
                  />
                )}
              </div>
            );
          })}
        </div>

        {/* Save row */}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 20, alignItems: 'center', flexWrap: 'wrap' }}>
          <input
            value={compName}
            onChange={e => setCompName(e.target.value)}
            placeholder="Name this recipe…"
            style={{
              border: '2px solid var(--border-default)', borderRadius: 12, padding: '8px 14px',
              fontSize: 14, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--text-primary)',
              background: 'var(--surface-nested)', outline: 'none', width: 200,
            }}
          />
          <window.CozyButton color="terracotta" onClick={handleSave} disabled={!hasComp}>
            Save Recipe 📦
          </window.CozyButton>
          <window.CozyButton color="cream" onClick={() => setActiveComp({
            TOP: { championId: null, alternates: [] },
            JUNGLE: { championId: null, alternates: [] },
            MID: { championId: null, alternates: [] },
            ADC: { championId: null, alternates: [] },
            SUPPORT: { championId: null, alternates: [] },
          })}>
            Clear 🗑️
          </window.CozyButton>
        </div>
      </div>

      {/* Analysis section */}
      {analysis ? (
        <div className="responsive-two-column">
          {/* Left: Vibe + Stats */}
          <div>
            {/* Vibe badge */}
            <div className="cozy-card" style={{ padding: 20, marginBottom: 16, textAlign: 'center' }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-muted)', marginBottom: 8, letterSpacing: 1 }}>COMP VIBE</div>
              <div className="fredoka" style={{ fontSize: 32, color: 'var(--accent-orange)', marginBottom: 8 }}>{analysis.vibe}</div>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1.5 }}>
                This team wins by <strong>{analysis.winCond}</strong><br />
                — best played <strong>{analysis.timing}</strong> game 🌟
              </div>
            </div>

            {/* Stat bars */}
            <div className="cozy-card" style={{ padding: 16 }}>
              <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 16, marginBottom: 12 }}>📊 Team Stats</div>
              <window.StatBar label="Crowd Control 🌀" value={analysis.stats.cc} color={statColors.cc} />
              <window.StatBar label="Frontline Strength 🛡️" value={analysis.stats.frontline} color={statColors.frontline} />
              <window.StatBar label="Engage Power ⚡" value={analysis.stats.engage} color={statColors.engage} />
              <window.StatBar label="Late Game Scaling 📈" value={analysis.stats.lateGame} color={statColors.lateGame} />
              <window.StatBar label="Bot Lane Safety 💛" value={analysis.stats.botSafety} color={statColors.botSafety} />
            </div>
          </div>

          {/* Right: Pros + Cons */}
          <div>
            <div className="cozy-card" style={{ padding: 16, marginBottom: 16 }}>
              <div className="fredoka" style={{ color: 'var(--accent-green)', fontSize: 16, marginBottom: 10 }}>🍃 Strengths</div>
              {analysis.pros.length > 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {analysis.pros.map((p, i) => (
                    <window.Tag key={i} color="green">{p}</window.Tag>
                  ))}
                </div>
              ) : (
                <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700 }}>No notable strengths yet 🌱</div>
              )}
            </div>

            <div className="cozy-card" style={{ padding: 16 }}>
              <div className="fredoka" style={{ color: '#F2A7C3', fontSize: 16, marginBottom: 10 }}>🌸 Weaknesses</div>
              {analysis.cons.length > 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {analysis.cons.map((c, i) => (
                    <window.Tag key={i} color="pink">{c}</window.Tag>
                  ))}
                </div>
              ) : (
                <div style={{ color: 'var(--accent-green)', fontSize: 13, fontWeight: 700 }}>No major weaknesses — nice! 🎉</div>
              )}
            </div>
          </div>
        </div>
      ) : (
        <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 }}>Kitchen's empty!</div>
          <div style={{ color: 'var(--text-muted)', fontWeight: 700 }}>
            Pick champions above to see your team recipe analysis appear here ✨
          </div>
        </div>
      )}

      {/* Crew notes on the WIP comp — bundled in when the recipe is saved */}
      <div className="cozy-card" style={{ padding: 18, marginTop: 16 }}>
        <window.CompNotes
          notes={activeCompNotes || []}
          onAdd={addActiveCompNote}
          onEdit={editActiveCompNote}
          onDelete={deleteActiveCompNote}
          title="Crew notes on this recipe"
          emoji="💬"
          placeholder="What's the plan with this comp?"
        />
        {(activeCompNotes && activeCompNotes.length > 0) && (
          <div style={{
            marginTop: 10, paddingTop: 10,
            borderTop: '1.5px dashed var(--border-default)',
            display: 'flex', alignItems: 'center', gap: 6,
            fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
          }}>
            <window.CrystalSparkle size={12} color="var(--accent-orange)" />
            These notes will travel with the comp when you save it 📦
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TeamComp });
