// MedBridge — applicants board (freelance-platform-style shortlisting)

const { useState: useSt3 } = React;

function ApplicantsBoard({ listing, onBack, onChat, onCall }) {
  const isV = listing.type === 'Vertretung';
  const baseApps = isV ? SAMPLE.applicants : SAMPLE.applicantsAusbildung;
  const t = isV ? MB.vertretung : MB.ausbildung;

  // Enrich each applicant with status state + match score
  const [apps, setApps] = useSt3(() => baseApps.map((a, i) => ({
    ...a,
    status: i === 0 ? 'shortlist' : i === baseApps.length - 1 ? 'declined' : 'new',
    match: a.match || [88, 76, 64, 71][i] || 70,
    appliedAgo: ['vor 14 Min', 'vor 2 Std', 'gestern', 'vor 3 Tagen'][i] || 'vor 1 Tag',
    motivation: a.motivation || [
      'Praxis ist gut erreichbar und Ihre Patientenstruktur passt zu meinem Vertretungsprofil.',
      'Freue mich auf Innomed NOVA — habe ich zwei Jahre verwendet.',
      'Verfügbar im genannten Zeitraum, flexibel bei Stundenanpassung.',
      'Würde gerne langfristig in Wien Fuß fassen.',
    ][i] || 'Motivationsschreiben verfügbar.',
  })));

  const [filter, setFilter] = useSt3('all');
  const [sort, setSort] = useSt3('match');
  const [openId, setOpenId] = useSt3(null);
  const [selectedWinner, setSelectedWinner] = useSt3(null);

  const counts = {
    all: apps.length,
    new: apps.filter(a => a.status === 'new').length,
    shortlist: apps.filter(a => a.status === 'shortlist').length,
    declined: apps.filter(a => a.status === 'declined').length,
  };

  const visible = apps
    .filter(a => filter === 'all' || a.status === filter)
    .sort((a, b) => sort === 'match' ? b.match - a.match : sort === 'rating' ? (b.rating || 0) - (a.rating || 0) : 0);

  const setStatus = (id, status) => setApps(xs => xs.map(a => a.id === id ? { ...a, status } : a));
  const openApp = apps.find(a => a.id === openId);

  if (selectedWinner) {
    return <SelectedSuccess listing={listing} doctor={selectedWinner} t={t}
      onBack={() => { setSelectedWinner(null); onBack && onBack(); }} />;
  }

  return (
    <div style={{ background: MB.surface.canvas, minHeight: '100%', paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ padding: '52px 16px 12px', background: MB.surface.raised, borderBottom: `1px solid ${MB.line.hair}`, position: 'sticky', top: 0, zIndex: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={onBack} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0 }}>
            <Icon name="chevron-l" size={24} color={MB.brand[700]} />
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <TypePill type={listing.type} subtype={listing.subtype} size="sm" />
            </div>
            <div style={{ marginTop: 4, fontFamily: MB.font, fontSize: 15, fontWeight: 700, color: MB.ink.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{listing.title}</div>
          </div>
          <button style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, color: MB.brand[700] }}>
            <Icon name="sort" size={20} />
          </button>
        </div>

        {/* Status filter tabs */}
        <div style={{ marginTop: 14, display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2, scrollbarWidth: 'none' }}>
          {[
            { id: 'all',       label: 'Alle' },
            { id: 'new',       label: 'Neu' },
            { id: 'shortlist', label: 'Shortlist' },
            { id: 'declined',  label: 'Abgelehnt' },
          ].map(f => {
            const active = filter === f.id;
            return (
              <button key={f.id} onClick={() => setFilter(f.id)} style={{
                border: `1.5px solid ${active ? t[600] : MB.line.hair}`,
                background: active ? t[50] : MB.surface.raised,
                color: active ? t[700] : MB.ink.secondary,
                padding: '6px 12px', borderRadius: 999, cursor: 'pointer',
                fontFamily: MB.font, fontSize: 13, fontWeight: 600, letterSpacing: -0.05, whiteSpace: 'nowrap',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                {f.label}
                <span style={{ fontVariantNumeric: 'tabular-nums', opacity: 0.7 }}>{counts[f.id]}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Summary banner */}
      <div style={{ padding: '12px 20px 0' }}>
        <div style={{ padding: '10px 12px', background: t[50], border: `1px solid ${t[100]}`, borderRadius: 12, display: 'flex', gap: 10, alignItems: 'center' }}>
          <Icon name="users" size={18} color={t[700]} />
          <div style={{ flex: 1, fontFamily: MB.font, fontSize: 13, color: t[700], lineHeight: 1.35 }}>
            <b>{counts.shortlist} auf Shortlist</b> · {counts.new} neue Bewerbungen ungelesen · Auswahl bis 22. Aug
          </div>
        </div>
      </div>

      {/* Sort row */}
      <div style={{ padding: '14px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: MB.font, fontSize: 13, color: MB.ink.tertiary }}>{visible.length} Bewerbungen</span>
        <div style={{ display: 'flex', gap: 6 }}>
          {[['match','Match'],['rating','Bewertung'],['new','Neueste']].map(([id, l]) => (
            <button key={id} onClick={() => setSort(id)} style={{
              border: 'none', background: 'transparent', cursor: 'pointer',
              padding: '4px 8px', borderRadius: 6,
              fontFamily: MB.font, fontSize: 12, fontWeight: 600,
              color: sort === id ? MB.brand[700] : MB.ink.tertiary,
              textDecoration: sort === id ? 'underline' : 'none',
              textUnderlineOffset: 3,
            }}>{l}</button>
          ))}
        </div>
      </div>

      {/* Cards */}
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {visible.map(a => (
          <ApplicantCard key={a.id} a={a} tone={t}
            onOpen={() => setOpenId(a.id)}
            onChat={() => onChat && onChat(a)}
            onCall={() => onCall && onCall(a)}
            onShortlist={() => setStatus(a.id, 'shortlist')}
            onDecline={() => setStatus(a.id, 'declined')}
            onRestore={() => setStatus(a.id, 'new')}
          />
        ))}
      </div>

      {/* Detail sheet */}
      {openApp && <ApplicantSheet a={openApp} tone={t} listing={listing}
        onClose={() => setOpenId(null)}
        onChat={() => { onChat && onChat(openApp); setOpenId(null); }}
        onCall={() => { onCall && onCall(openApp); setOpenId(null); }}
        onShortlist={() => { setStatus(openApp.id, 'shortlist'); }}
        onDecline={() => { setStatus(openApp.id, 'declined'); setOpenId(null); }}
        onSelect={() => { setSelectedWinner(openApp); setOpenId(null); }}
      />}
    </div>
  );
}

function ApplicantCard({ a, tone, onOpen, onChat, onCall, onShortlist, onDecline, onRestore }) {
  const declined = a.status === 'declined';
  const shortlisted = a.status === 'shortlist';
  return (
    <div onClick={onOpen} style={{
      background: MB.surface.raised,
      border: `1px solid ${shortlisted ? tone[600] : MB.line.hair}`,
      borderLeft: shortlisted ? `4px solid ${tone[600]}` : `1px solid ${MB.line.hair}`,
      borderRadius: 14, padding: 14, cursor: 'pointer',
      boxShadow: MB.shadow.card, opacity: declined ? 0.55 : 1, position: 'relative',
    }}>
      {a.status === 'new' && (
        <span style={{ position: 'absolute', top: -6, right: 12, padding: '2px 8px', background: tone[600], color: '#fff', borderRadius: 999, fontFamily: MB.font, fontSize: 10, fontWeight: 700, letterSpacing: 0.4 }}>NEU</span>
      )}
      {shortlisted && (
        <span style={{ position: 'absolute', top: -6, right: 12, padding: '2px 8px', background: tone[700], color: '#fff', borderRadius: 999, fontFamily: MB.font, fontSize: 10, fontWeight: 700, letterSpacing: 0.4, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Icon name="star" size={10} color="#fff" />SHORTLIST
        </span>
      )}

      <div style={{ display: 'flex', gap: 12 }}>
        <Avatar name={a.name} size={52} verified={a.verified} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: MB.font, fontSize: 16, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.1 }}>{a.name}</div>
          <div style={{ marginTop: 2, display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
            <CareerChip stage={a.stage} size="sm" />
            {a.rating && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontFamily: MB.font, fontSize: 12, color: MB.ink.secondary }}>
                <Icon name="star" size={11} color="#E0A93D" /> {a.rating} <span style={{ color: MB.ink.tertiary }}>({a.ratings})</span>
              </span>
            )}
            <span style={{ fontFamily: MB.font, fontSize: 12, color: MB.ink.tertiary }}>· {a.appliedAgo}</span>
          </div>
          <div style={{ marginTop: 6, fontFamily: MB.font, fontSize: 13, color: MB.ink.secondary, lineHeight: 1.4, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
            {a.motivation}
          </div>
        </div>
        <MatchRing pct={a.match} color={tone[600]} />
      </div>

      <div style={{ marginTop: 12, display: 'flex', gap: 8 }} onClick={(e) => e.stopPropagation()}>
        {!declined && (
          <>
            <button onClick={onCall} style={iconBtn(MB.line.hair)}><Icon name="phone" size={16} color={MB.ink.primary} /></button>
            <button onClick={onChat} style={iconBtn(MB.line.hair)}><Icon name="message" size={16} color={MB.ink.primary} /></button>
            {shortlisted ? (
              <Button kind="secondary" size="sm" onClick={onDecline}>Aus Shortlist</Button>
            ) : (
              <Button kind="secondary" size="sm" leading={<Icon name="star-o" size={14} />} onClick={onShortlist}>Shortlist</Button>
            )}
            <div style={{ flex: 1 }} />
            <button onClick={onDecline} style={{ ...iconBtn(MB.line.hair), color: MB.ink.tertiary }}><Icon name="x" size={16} color={MB.ink.tertiary} /></button>
          </>
        )}
        {declined && (
          <Button kind="ghost" size="sm" onClick={onRestore}>Wiederherstellen</Button>
        )}
      </div>
    </div>
  );
}

function iconBtn(border) {
  return {
    width: 36, height: 36, borderRadius: 8, border: `1px solid ${border}`,
    background: '#fff', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  };
}

function MatchRing({ pct, color }) {
  const r = 18, c = 2 * Math.PI * r;
  const dash = (pct / 100) * c;
  return (
    <div style={{ position: 'relative', width: 44, height: 44, flexShrink: 0 }}>
      <svg width="44" height="44" viewBox="0 0 44 44">
        <circle cx="22" cy="22" r={r} stroke={MB.surface.canvas2} strokeWidth="4" fill="none" />
        <circle cx="22" cy="22" r={r} stroke={color} strokeWidth="4" fill="none"
          strokeDasharray={`${dash} ${c}`} strokeLinecap="round"
          transform="rotate(-90 22 22)" />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: MB.font, fontSize: 11, fontWeight: 700, color: MB.ink.primary, fontVariantNumeric: 'tabular-nums' }}>
        {pct}<span style={{ fontSize: 8, color: MB.ink.tertiary }}>%</span>
      </div>
    </div>
  );
}

function ApplicantSheet({ a, tone, listing, onClose, onChat, onCall, onShortlist, onDecline, onSelect }) {
  const isAusbildung = listing.type !== 'Vertretung';
  return (
    <div style={{ position: 'absolute', inset: 0, background: MB.surface.overlay, zIndex: 70, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div style={{ background: MB.surface.canvas, borderTopLeftRadius: 20, borderTopRightRadius: 20, maxHeight: '94%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '8px 0 4px', display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: 44, height: 5, background: MB.line.border, borderRadius: 3 }} />
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '12px 20px 20px' }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <Avatar name={a.name} size={72} verified={a.verified} />
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: MB.font, fontSize: 20, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.2 }}>{a.name}</div>
              <div style={{ marginTop: 6, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                <CareerChip stage={a.stage} size="sm" />
                <Chip tone="success" size="sm" leading={<Icon name="badge-check" size={12} />}>ID Austria</Chip>
              </div>
            </div>
            <MatchRing pct={a.match} color={tone[600]} />
          </div>

          {/* Quick actions */}
          <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
            <Button kind="primary" full size="md" tone={tone} leading={<Icon name="message" size={16} color="#fff" />} onClick={onChat}>Chat</Button>
            <Button kind="secondary" full size="md" leading={<Icon name="phone" size={16} />} onClick={onCall}>Anrufen</Button>
          </div>

          {/* Match breakdown */}
          <div style={{ marginTop: 18, padding: 14, background: MB.surface.raised, border: `1px solid ${MB.line.hair}`, borderRadius: 12 }}>
            <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 10 }}>Match · {a.match}%</div>
            {[
              ['Fach passt', 'Allgemeinmedizin', true],
              ['Zeitraum verfügbar', isAusbildung ? 'ab Okt 2026' : '18.–29. Aug', true],
              ['Region erreichbar', 'Wien · ' + (a.distance || '4,2 km'), true],
              [isAusbildung ? 'Karrierestufe' : 'Erfahrung', isAusbildung ? '3. Studienjahr' : '6 Jahre Vertretung', true],
              ['Sprache(n)', 'DE · EN', true],
              ['IT-System Erfahrung', 'Innomed NOVA', a.match > 75],
            ].map(([k, v, ok], i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0' }}>
                <Icon name={ok ? 'check-circle' : 'info'} size={16} color={ok ? MB.success[600] : MB.warning[600]} />
                <span style={{ flex: 1, fontFamily: MB.font, fontSize: 13, color: MB.ink.primary }}>{k}</span>
                <span style={{ fontFamily: MB.font, fontSize: 13, color: MB.ink.secondary }}>{v}</span>
              </div>
            ))}
          </div>

          {/* Motivation */}
          <div style={{ marginTop: 16 }}>
            <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 8 }}>Motivation</div>
            <div style={{ fontFamily: MB.font, fontSize: 15, color: MB.ink.primary, lineHeight: 1.5, padding: 14, background: MB.surface.raised, border: `1px solid ${MB.line.hair}`, borderRadius: 12 }}>
              {a.motivation}
            </div>
          </div>

          {/* Qualifications */}
          <div style={{ marginTop: 16 }}>
            <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 8 }}>{isAusbildung ? 'Studium & Rotationen' : 'Qualifikationen'}</div>
            <div style={{ background: MB.surface.raised, border: `1px solid ${MB.line.hair}`, borderRadius: 12, overflow: 'hidden' }}>
              {(isAusbildung ? [
                ['MedUni Wien · 5. Studienjahr', '2024 – heute'],
                ['Klinik-Rotation Innere', '6 Wochen · KH Hietzing'],
                ['Klinik-Rotation Chirurgie', '4 Wochen · AKH'],
              ] : [
                ['Facharzt Allgemeinmedizin', '2018 · MedUni Wien'],
                ['Notfallmedizin-Diplom ÖÄK', '2020'],
                ['Vertretungserfahrung', '6 Jahre · 34 Praxen'],
              ]).map((r, i, arr) => (
                <div key={i} style={{ padding: '10px 14px', borderBottom: i < arr.length - 1 ? `1px solid ${MB.line.hair}` : 'none', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ fontFamily: MB.font, fontSize: 14, fontWeight: 600, color: MB.ink.primary }}>{r[0]}</span>
                  <span style={{ fontFamily: MB.font, fontSize: 12, color: MB.ink.tertiary }}>{r[1]}</span>
                </div>
              ))}
            </div>
          </div>

          {a.rating && (
            <div style={{ marginTop: 16 }}>
              <div style={{ fontFamily: MB.font, fontSize: 12, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: MB.ink.tertiary, marginBottom: 8 }}>Bewertungen · {a.rating} ({a.ratings})</div>
              <div style={{ background: MB.surface.raised, border: `1px solid ${MB.line.hair}`, borderRadius: 12, padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
                  {[1,2,3,4,5].map(s => <Icon key={s} name="star" size={14} color={s <= Math.round(a.rating) ? '#E0A93D' : MB.line.border} />)}
                </div>
                <div style={{ fontFamily: MB.font, fontSize: 14, color: MB.ink.primary, lineHeight: 1.5, fontStyle: 'italic' }}>
                  „Pünktlich, sehr gute Patientenkommunikation, EDV-Übergabe lief reibungslos."
                </div>
                <div style={{ marginTop: 6, fontFamily: MB.font, fontSize: 12, color: MB.ink.tertiary }}>Dr. K. Engelmann · Wien · Mär 2026</div>
              </div>
            </div>
          )}
        </div>

        {/* Sticky footer */}
        <div style={{ padding: '12px 20px 30px', background: MB.surface.canvas, borderTop: `1px solid ${MB.line.hair}` }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            <Button kind="secondary" full size="md" leading={<Icon name="x" size={14} />} onClick={onDecline}>Ablehnen</Button>
            <Button kind="secondary" full size="md" leading={<Icon name="star-o" size={14} />} onClick={onShortlist}>Shortlist</Button>
          </div>
          <Button kind="primary" full size="lg" tone={tone} leading={<Icon name="thumb-up" size={16} color="#fff" />} onClick={onSelect}>
            Auswählen & beauftragen
          </Button>
          <div style={{ marginTop: 8, textAlign: 'center', fontFamily: MB.font, fontSize: 11, color: MB.ink.tertiary }}>
            Beide Seiten erhalten den verbindlichen Vertragsentwurf zur Unterzeichnung.
          </div>
        </div>
      </div>
      <div onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, width: 36, height: 36, borderRadius: 999, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
        <Icon name="x" size={18} color="#fff" />
      </div>
    </div>
  );
}

function SelectedSuccess({ listing, doctor, t, onBack }) {
  return (
    <div style={{ background: MB.surface.canvas, height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px', textAlign: 'center' }}>
        <div style={{ width: 88, height: 88, borderRadius: 999, background: t[50], display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18, border: `2px solid ${t[100]}` }}>
          <Icon name="thumb-up" size={42} color={t[600]} stroke={2} />
        </div>
        <div style={{ fontFamily: MB.font, fontSize: 24, fontWeight: 700, color: MB.ink.primary, letterSpacing: -0.3, lineHeight: 1.15 }}>
          {doctor.name} ausgewählt
        </div>
        <div style={{ marginTop: 10, fontFamily: MB.font, fontSize: 15, color: MB.ink.secondary, lineHeight: 1.5, maxWidth: 300 }}>
          Beide Seiten erhalten jetzt den Vertragsentwurf. Andere Bewerber:innen werden automatisch und respektvoll informiert.
        </div>

        <div style={{ marginTop: 26, padding: 14, background: MB.surface.raised, border: `1px solid ${MB.line.hair}`, borderRadius: 14, width: '100%', maxWidth: 320, boxShadow: MB.shadow.card }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
            <TypePill type={listing.type} subtype={listing.subtype} size="sm" />
            <span style={{ fontFamily: MB.font, fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: t[700] }}>Bestätigt</span>
          </div>
          <div style={{ fontFamily: MB.font, fontSize: 14, fontWeight: 600, color: MB.ink.primary, textAlign: 'left' }}>{listing.title}</div>
          <div style={{ marginTop: 10, display: 'flex', gap: 10, alignItems: 'center' }}>
            <Avatar name={doctor.name} size={36} verified />
            <div style={{ flex: 1, textAlign: 'left' }}>
              <div style={{ fontFamily: MB.font, fontSize: 13, fontWeight: 600, color: MB.ink.primary }}>{doctor.name}</div>
              <div style={{ fontFamily: MB.font, fontSize: 11, color: MB.ink.tertiary }}>Vertragsentwurf gesendet · 14:32</div>
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '14px 20px 30px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Button kind="primary" full size="lg" tone={t}>Vertrag öffnen</Button>
        <Button kind="ghost" full size="md" onClick={onBack}>Zurück zu meinen Inseraten</Button>
      </div>
    </div>
  );
}

Object.assign(window, { ApplicantsBoard });
