
// ClashSchedule.jsx — Community Board / Corkboard
const { useState } = React;
const { useApp } = window;

const CLASH_EVENTS = [
  { id: 'demacia', name: 'Demacia Cup 🏆', date: '2026-01-24', endDate: '2026-01-25', format: 'SR', emoji: '🏆' },
  { id: 'ionia',   name: 'Ionia Cup 🌊',   date: '2026-02-21', endDate: '2026-02-22', format: 'ARAM', emoji: '🌊' },
  { id: 'ixtal',   name: 'Ixtal Cup 🌿',   date: '2026-04-18', endDate: '2026-04-19', format: 'ARAM', emoji: '🌿' },
  { id: 'noxus',   name: 'Noxus Cup ⚔️',   date: '2026-05-16', endDate: '2026-05-17', format: 'SR',   emoji: '⚔️' },
  { id: 'freljord',name: 'Freljord Cup ❄️', date: '2026-06-20', endDate: '2026-06-21', format: 'SR',   emoji: '❄️' },
];

const READINESS_FIELDS = [
  { key: 'level30',  label: 'Level 30 ✅' },
  { key: 'ranked',   label: 'Ranked Done 🎖️' },
  { key: 'sms',      label: 'SMS Verified 📱' },
];

function EventCard({ event }) {
  const now = new Date();
  const startDate = new Date(event.date);
  const endDate = new Date(event.endDate);
  const daysAway = Math.ceil((startDate - now) / (1000 * 60 * 60 * 24));
  const isPast = endDate < now;
  const isNow = startDate <= now && now <= endDate;

  let countdownText = '';
  let countdownColor = 'var(--accent-orange)';
  if (isPast) { countdownText = 'Finished 🌿'; countdownColor = 'var(--text-muted)'; }
  else if (isNow) { countdownText = '🎉 HAPPENING NOW!'; countdownColor = '#7CBF8E'; }
  else if (daysAway <= 7) { countdownText = `${daysAway} day${daysAway !== 1 ? 's' : ''} away! ⚡`; countdownColor = '#F2A7C3'; }
  else { countdownText = `${daysAway} days away`; }

  return (
    <div className="cozy-card" style={{
      padding: 16, opacity: isPast ? 0.65 : 1,
      transform: isPast ? 'none' : 'rotate(-0.5deg)',
      transition: 'all 0.2s',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 8 }}>
        <div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18 }}>{event.name}</div>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>
            {startDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}–
            {endDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
          </div>
        </div>
        <div style={{
          background: event.format === 'ARAM' ? '#C5B4E3' : '#F7DFA0',
          border: '1.5px solid var(--border-default)', borderRadius: 12,
          padding: '3px 10px', fontSize: 11, fontWeight: 800, color: 'var(--text-on-light)',
        }}>
          {event.format}
        </div>
      </div>
      <div style={{ fontSize: 13, fontWeight: 800, color: countdownColor }}>{countdownText}</div>
    </div>
  );
}

function ClashSchedule() {
  const { players, clashReadiness, updateClashReadiness, POSITION_EMOJIS, sessionUserId, myUserId } = useApp();

  const totalBoxes = players.length * READINESS_FIELDS.length;
  const checkedCount = players.reduce((acc, player) => {
    const pr = clashReadiness[player.id] || {};
    return acc + READINESS_FIELDS.filter(f => pr[f.key]).length;
  }, 0);

  const allReady = checkedCount === totalBoxes;

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Clash Schedule 📅
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Community board — pin your readiness & track upcoming events!
      </p>

      <div className="responsive-two-column">
        {/* Left: Events corkboard */}
        <div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18, marginBottom: 12 }}>
            📌 Upcoming Events
          </div>
          <div style={{
            background: 'var(--surface-nested)', border: '3px solid var(--border-emphasis)', borderRadius: 20,
            padding: 16, display: 'flex', flexDirection: 'column', gap: 12,
            boxShadow: 'inset 0 2px 8px var(--border-default)',
          }}>
            {CLASH_EVENTS.map(event => (
              <EventCard key={event.id} event={event} />
            ))}
          </div>
        </div>

        {/* Right: Team readiness */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18 }}>
              🌸 Team Readiness
            </div>
            <span style={{ fontSize: 13, fontWeight: 800, color: '#7CBF8E' }}>
              {checkedCount}/{totalBoxes} ready
            </span>
          </div>

          {/* Progress bar */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ height: 12, background: 'var(--border-default)', borderRadius: 20, overflow: 'hidden', border: '1.5px solid var(--border-default)' }}>
              <div style={{
                height: '100%',
                width: `${(checkedCount / totalBoxes) * 100}%`,
                background: allReady ? '#7CBF8E' : '#F7DFA0',
                borderRadius: 20, transition: 'all 0.5s cubic-bezier(0.34, 1.2, 0.64, 1)',
              }}></div>
            </div>
          </div>

          {/* All ready banner */}
          {allReady && (
            <div style={{
              background: '#B8E0C0', border: '2px solid #7CBF8E', borderRadius: 16,
              padding: '12px 20px', marginBottom: 16, textAlign: 'center',
            }}>
              <div className="fredoka" style={{ color: '#2d6b47', fontSize: 20 }}>
                Team is READY! 🎉
              </div>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#2d6b47' }}>
                All 5 players are cleared to Clash!
              </div>
            </div>
          )}

          {/* Player rows */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {players.map(player => {
              const pr = clashReadiness[player.id] || {};
              const playerReady = READINESS_FIELDS.every(f => pr[f.key]);
              const isMe = !!(player.ownerId && player.ownerId === sessionUserId);
              return (
                <div key={player.id} className="cozy-card" style={{ padding: 14 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                    <span style={{ fontSize: 18 }}>{POSITION_EMOJIS[player.position]}</span>
                    <span className="fredoka" style={{ fontSize: 15, color: 'var(--text-primary)' }}>{player.name}</span>
                    {playerReady && (
                      <span style={{
                        background: '#B8E0C0', border: '1.5px solid #7CBF8E',
                        borderRadius: 10, fontSize: 10, fontWeight: 800, padding: '1px 8px',
                        color: '#2d6b47', fontFamily: 'Nunito', marginLeft: 'auto',
                      }}>Ready ✓</span>
                    )}
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {READINESS_FIELDS.map(field => {
                      const checked = !!pr[field.key];
                      return (
                        <label key={field.key} style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: isMe ? 'pointer' : 'default' }}>
                          <div
                            onClick={isMe ? () => updateClashReadiness(player.id, field.key, !checked) : undefined}
                            style={{
                              width: 20, height: 20, borderRadius: 6,
                              border: `2.5px solid ${checked ? '#7CBF8E' : 'var(--border-default)'}`,
                              background: checked ? '#7CBF8E' : 'var(--surface-nested)',
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              fontSize: 12, cursor: isMe ? 'pointer' : 'default', transition: 'all 0.2s',
                              flexShrink: 0,
                            }}
                          >
                            {checked ? '✓' : ''}
                          </div>
                          <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>
                            {field.label}
                          </span>
                        </label>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClashSchedule });
