// trip-detail.jsx — RSVP, chores, ics export panel

function Avatar({ member, size = 32, status }) {
  const bg = status === 'yes' ? '#5a6a3e'
           : status === 'maybe' ? '#8a7858'
           : status === 'no' ? '#3a342a'
           : '#2a241c';
  return (
    <div className="avatar" style={{
      width: size, height: size, borderRadius: '50%',
      background: bg, color: '#f5ecd6',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-mono)', fontSize: size * 0.32,
      letterSpacing: '0.02em',
      border: '0.5px solid rgba(201,161,74,.3)',
      flexShrink: 0,
    }} title={member.name}>
      {member.initials}
    </div>
  );
}

function ChoreIcon({ kind, size = 14 }) {
  const props = { width: size, height: size, fill: 'none', stroke: 'currentColor',
                  strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'lunch') return (
    <svg viewBox="0 0 24 24" {...props}>
      <path d="M4 12 a8 4 0 0 1 16 0 z"/>
      <line x1="4" y1="12" x2="20" y2="12"/>
      <line x1="3" y1="15" x2="21" y2="15"/>
    </svg>
  );
  if (kind === 'dinner') return (
    <svg viewBox="0 0 24 24" {...props}>
      <circle cx="12" cy="12" r="7"/>
      <line x1="6" y1="3" x2="6" y2="9"/>
      <line x1="18" y1="3" x2="18" y2="9"/>
    </svg>
  );
  if (kind === 'dishes') return (
    <svg viewBox="0 0 24 24" {...props}>
      <path d="M5 7 L 5 18 L 19 18 L 19 7"/>
      <path d="M3 7 L 21 7"/>
      <path d="M9 11 L 15 11"/>
    </svg>
  );
  if (kind === 'prep') return (
    <svg viewBox="0 0 24 24" {...props}>
      <path d="M7 4 L 4 7 L 14 17 L 17 14 Z"/>
      <line x1="13" y1="13" x2="20" y2="20"/>
      <line x1="17" y1="14" x2="20" y2="11"/>
    </svg>
  );
  if (kind === 'cleanup') return (
    <svg viewBox="0 0 24 24" {...props}>
      <path d="M5 7 L 19 7 L 18 20 L 6 20 Z"/>
      <line x1="3" y1="7" x2="21" y2="7"/>
      <path d="M9 7 L 9 4 L 15 4 L 15 7"/>
    </svg>
  );
  return null;
}

function RsvpButton({ value, current, onClick, children }) {
  const isActive = current === value;
  return (
    <button type="button" onClick={onClick}
            className={`rsvp-btn ${isActive ? 'is-active' : ''} rsvp-${value}`}>
      {children}
    </button>
  );
}

function TripDetail({ trip, rsvps, chores, choreAssignments, choreNotes, onRsvp, onChoreToggle, onChoreNote, currentUserId }) {
  const [editingNoteFor, setEditingNoteFor] = React.useState(null);
  const [draftNote, setDraftNote] = React.useState('');
  const tripChores = window.choresForTrip(trip);
  const yesMembers = window.MEMBERS.filter((m) => rsvps[m.id] === 'yes');
  const maybeMembers = window.MEMBERS.filter((m) => rsvps[m.id] === 'maybe');
  const noMembers = window.MEMBERS.filter((m) => rsvps[m.id] === 'no');
  const noResponseMembers = window.MEMBERS.filter((m) => !rsvps[m.id]);

  const myRsvp = rsvps[currentUserId];
  const canTakeChores = myRsvp === 'yes';

  // Group chores by day
  const choresByDay = {};
  tripChores.forEach((c) => {
    if (!choresByDay[c.day]) choresByDay[c.day] = [];
    choresByDay[c.day].push(c);
  });

  return (
    <div className="trip-detail">
      <div className="td-header">
        <div className="td-header-meta">
          <div className="td-eyebrow">
            <span className="td-anchor-tag">{trip.anchor ? '★ Årets anker' : `Tur ${trip.quadrant + 1} af 4`}</span>
            <span className="td-divider">·</span>
            <span>{trip.subtitle}</span>
          </div>
          <h2 className="td-title">{trip.name}</h2>
          <p className="td-epigraph">{trip.epigraph}</p>
        </div>
        <button className="td-ics" onClick={() => window.downloadIcs(trip)}
                title="Tilføj til kalender">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none"
               stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
            <rect x="4" y="6" width="16" height="14" rx="1"/>
            <line x1="4" y1="10" x2="20" y2="10"/>
            <line x1="9" y1="3" x2="9" y2="7"/>
            <line x1="15" y1="3" x2="15" y2="7"/>
          </svg>
          <span>Tilføj til kalender</span>
        </button>
      </div>

      <div className="td-facts">
        <div className="td-fact">
          <div className="td-fact-label">DATO</div>
          <div className="td-fact-value">{window.fmtDateRange(trip.start, trip.end)}</div>
        </div>
        <div className="td-fact">
          <div className="td-fact-label">LOKATION</div>
          <div className="td-fact-value">{trip.location}</div>
        </div>
        <div className="td-fact">
          <div className="td-fact-label">MOTIV</div>
          <div className="td-fact-value td-fact-italic">{trip.motif}</div>
        </div>
      </div>

      {/* RSVP section */}
      <section className="td-section">
        <div className="td-section-head">
          <h3>Fremmøde</h3>
          <div className="td-section-rule"></div>
          <span className="td-section-meta">
            {yesMembers.length} af {window.MEMBERS.length} bekræftet
          </span>
        </div>

        <div className="rsvp-self">
          <span className="rsvp-self-lbl">Du svarer som <em>{window.MEMBERS.find((m) => m.id === currentUserId)?.name}</em>:</span>
          <div className="rsvp-buttons">
            <RsvpButton value="yes" current={myRsvp} onClick={() => onRsvp(currentUserId, 'yes')}>
              Ja, jeg er der
            </RsvpButton>
            <RsvpButton value="maybe" current={myRsvp} onClick={() => onRsvp(currentUserId, 'maybe')}>
              Måske
            </RsvpButton>
            <RsvpButton value="no" current={myRsvp} onClick={() => onRsvp(currentUserId, 'no')}>
              Forhindret
            </RsvpButton>
          </div>
        </div>

        <div className="rsvp-roster">
          {yesMembers.length > 0 && (
            <div className="rsvp-row">
              <div className="rsvp-row-label">
                <span className="rsvp-dot rsvp-dot-yes"></span> Bekræftet
                <span className="rsvp-row-count">{yesMembers.length}</span>
              </div>
              <div className="rsvp-row-avatars">
                {yesMembers.map((m) => (
                  <div key={m.id} className="rsvp-chip">
                    <Avatar member={m} size={26} status="yes"/>
                    <span>{m.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {maybeMembers.length > 0 && (
            <div className="rsvp-row">
              <div className="rsvp-row-label">
                <span className="rsvp-dot rsvp-dot-maybe"></span> Måske
                <span className="rsvp-row-count">{maybeMembers.length}</span>
              </div>
              <div className="rsvp-row-avatars">
                {maybeMembers.map((m) => (
                  <div key={m.id} className="rsvp-chip">
                    <Avatar member={m} size={26} status="maybe"/>
                    <span>{m.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {noMembers.length > 0 && (
            <div className="rsvp-row">
              <div className="rsvp-row-label">
                <span className="rsvp-dot rsvp-dot-no"></span> Forhindret
                <span className="rsvp-row-count">{noMembers.length}</span>
              </div>
              <div className="rsvp-row-avatars">
                {noMembers.map((m) => (
                  <div key={m.id} className="rsvp-chip rsvp-chip-no">
                    <Avatar member={m} size={26} status="no"/>
                    <span>{m.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {noResponseMembers.length > 0 && (
            <div className="rsvp-row rsvp-row-pending">
              <div className="rsvp-row-label">
                <span className="rsvp-dot rsvp-dot-pending"></span> Afventer svar
                <span className="rsvp-row-count">{noResponseMembers.length}</span>
              </div>
              <div className="rsvp-row-avatars">
                {noResponseMembers.map((m) => (
                  <div key={m.id} className="rsvp-chip rsvp-chip-pending">
                    <Avatar member={m} size={26}/>
                    <span>{m.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* Chores section */}
      <section className="td-section">
        <div className="td-section-head">
          <h3>Tjansefordeling</h3>
          <div className="td-section-rule"></div>
          <span className="td-section-meta">
            {Object.values(choreAssignments).reduce((acc, v) => {
              const arr = Array.isArray(v) ? v : (v ? [v] : []);
              return acc + (arr.length > 0 ? 1 : 0);
            }, 0)} af {tripChores.length} besat
          </span>
        </div>

        {!canTakeChores && (
          <div className="chore-locked">
            <em>Kun bekræftede deltagere kan påtage sig tjanser.</em>
          </div>
        )}

        <div className="chore-grid">
          {Object.entries(choresByDay).map(([day, dayChores]) => {
            const d = new Date(day + 'T00:00:00');
            const weekday = window.WEEKDAYS_LONG_DA[d.getDay()];
            return (
              <div key={day} className="chore-day">
                <div className="chore-day-head">
                  <span className="chore-day-weekday">{weekday}</span>
                  <span className="chore-day-date">{d.getDate()}. {window.MONTHS_SHORT_DA[d.getMonth()]}</span>
                </div>
                <div className="chore-list">
                  {dayChores.map((c) => {
                    const rawAssigned = choreAssignments[c.id];
                    // Normalize: array of memberIds
                    const assignedIds = Array.isArray(rawAssigned)
                      ? rawAssigned
                      : (rawAssigned ? [rawAssigned] : []);
                    const assignedMembers = assignedIds
                      .map((id) => window.MEMBERS.find((m) => m.id === id))
                      .filter(Boolean);
                    const isMine = assignedIds.includes(currentUserId);
                    const max = c.max || 3;
                    const isFull = assignedIds.length >= max;
                    const note = choreNotes?.[c.id] || '';
                    const isEditing = editingNoteFor === c.id;
                    const placeholder = c.icon === 'lunch'
                      ? 'fx. rugbrødsmadder med rester, sild & æg…'
                      : c.icon === 'dinner'
                        ? 'fx. coq au vin, hjortefilet, BBQ…'
                        : c.icon === 'prep'
                          ? 'fx. køber ind, tænder kaminen, gør senge klar…'
                          : c.icon === 'cleanup'
                            ? 'fx. støvsuger, tømmer skraldespande, vasker badeværelser…'
                            : 'fx. tager opvasken efter aftensmad';
                    const canClaim = canTakeChores && !isMine && !isFull;
                    return (
                      <div key={c.id} className={`chore-row ${assignedIds.length ? 'is-assigned' : ''} ${isMine ? 'is-mine' : ''}`}>
                        <div className="chore-row-main">
                          <div className="chore-row-icon">
                            <ChoreIcon kind={c.icon} size={16}/>
                          </div>
                          <div className="chore-row-type">
                            {c.type}
                            <span className="chore-row-meta">{assignedIds.length}/{max}</span>
                          </div>
                          <div className="chore-row-action">
                            {canClaim && (
                              <button className="chore-claim-btn"
                                      onClick={() => {
                                        onChoreToggle(c.id, currentUserId, 'add');
                                        if (assignedIds.length === 0) {
                                          setEditingNoteFor(c.id);
                                          setDraftNote('');
                                        }
                                      }}>
                                + Påtag mig
                              </button>
                            )}
                            {!canTakeChores && assignedIds.length === 0 && (
                              <span className="chore-row-pending">Ledig</span>
                            )}
                            {isFull && !isMine && (
                              <span className="chore-row-pending">Fuldt besat</span>
                            )}
                          </div>
                        </div>

                        {/* Assignees row */}
                        {assignedMembers.length > 0 && (
                          <div className="chore-assignees">
                            {assignedMembers.map((m) => (
                              <div key={m.id}
                                   className={`chore-assignee ${m.id === currentUserId ? 'is-me' : ''}`}
                                   onClick={() => m.id === currentUserId && onChoreToggle(c.id, m.id, 'remove')}
                                   title={m.id === currentUserId ? 'Klik for at slippe tjansen' : ''}>
                                <Avatar member={m} size={20} status="yes"/>
                                <span>{m.name}</span>
                                {m.id === currentUserId && <span className="chore-release">×</span>}
                              </div>
                            ))}
                            {!isFull && canTakeChores && !isMine && (
                              <button className="chore-assignee-add"
                                      onClick={() => onChoreToggle(c.id, currentUserId, 'add')}
                                      title="Slut dig til">+</button>
                            )}
                          </div>
                        )}

                        {/* Menu / note */}
                        {assignedIds.length > 0 && !isEditing && (
                          <div className="chore-note-row">
                            {note ? (
                              <div className="chore-note">
                                <span className="chore-note-label">{c.icon === 'dishes' || c.icon === 'cleanup' || c.icon === 'prep' ? 'Plan' : 'Menu'}</span>
                                <span className="chore-note-text">"{note}"</span>
                                {isMine && (
                                  <button className="chore-note-edit"
                                          onClick={() => { setEditingNoteFor(c.id); setDraftNote(note); }}>
                                    rediger
                                  </button>
                                )}
                              </div>
                            ) : isMine ? (
                              <button className="chore-note-add"
                                      onClick={() => { setEditingNoteFor(c.id); setDraftNote(''); }}>
                                + Tilføj {c.icon === 'dinner' || c.icon === 'lunch' ? 'menu' : 'plan'}
                              </button>
                            ) : (
                              <span className="chore-note-empty">— intet noteret endnu —</span>
                            )}
                          </div>
                        )}

                        {assignedIds.length > 0 && isEditing && (
                          <div className="chore-note-edit-row">
                            <span className="chore-note-label">
                              {c.icon === 'dinner' || c.icon === 'lunch'
                                ? 'Hvad tænker I at lave?'
                                : 'Hvad er planen?'}
                            </span>
                            <input
                              type="text"
                              className="chore-note-input"
                              value={draftNote}
                              autoFocus
                              placeholder={placeholder}
                              onChange={(e) => setDraftNote(e.target.value)}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  onChoreNote(c.id, draftNote.trim());
                                  setEditingNoteFor(null);
                                } else if (e.key === 'Escape') {
                                  setEditingNoteFor(null);
                                }
                              }}/>
                            <div className="chore-note-actions">
                              <button className="chore-note-btn primary"
                                      onClick={() => {
                                        onChoreNote(c.id, draftNote.trim());
                                        setEditingNoteFor(null);
                                      }}>Gem</button>
                              <button className="chore-note-btn"
                                      onClick={() => setEditingNoteFor(null)}>Annullér</button>
                            </div>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { TripDetail, Avatar, ChoreIcon });
