/* ============================================================
   SVLM — Our team (customer-facing staff directory)

   The old vanilla app had a candidate gallery reading GET /api/candidates;
   the React rewrite never carried it over, so the profiles staff fill in
   had no reader. This is that screen rebuilt in the current visual
   language, plus the two things the old one never showed: the star
   rating customers themselves produced, and photos of the equipment the
   person turns up with.

   Picking someone is not decoration — it writes bookings.requested_staff_id,
   which routes/staff.js already honours by narrowing the job to that one
   person instead of offering it to everyone eligible.
   ============================================================ */
const Ptm = window.PALETTE;
const Stm = window.SHAPE;

const TEAM_POSITION_LABELS = {
  // maid_type
  hourly: ['Hourly maid', 'แม่บ้านรายชั่วโมง'], live_in: ['Live-in maid', 'แม่บ้านประจำ'],
  laundry: ['Laundry & ironing', 'พนักงานซักผ้ารีดผ้า'], big_cleaning_team: ['Big Cleaning team', 'ทีม Big Cleaning'],
  nanny: ['Nanny', 'พี่เลี้ยงเด็ก'], elderly_caregiver: ['Elderly caregiver', 'ผู้ดูแลผู้สูงอายุ'],
  nurse: ['Nurse', 'พยาบาล'], housekeeping: ['Housekeeper', 'แม่บ้านทำความสะอาด'],
  driver: ['Driver', 'คนขับรถ'],
  // trade
  wallpaper: ['Wallpaper', 'ช่างติดวอลเปเปอร์'], electrical: ['Electrician', 'ช่างไฟฟ้า'],
  tiling: ['Tiling', 'ช่างปูกระเบื้อง'], ceiling: ['Ceilings', 'ช่างฝ้าเพดาน'],
  plumbing: ['Plumber', 'ช่างประปา'], painting: ['Painter', 'ช่างทาสี'],
  aircon: ['Aircon technician', 'ช่างแอร์'], cctv: ['CCTV', 'ช่างติดตั้งกล้อง CCTV'],
  solarcell: ['Solar Cell', 'ช่างติดตั้ง Solar Cell'], evcharger: ['EV Charger', 'ช่างติดตั้ง EV Charger'],
  waterpump: ['Water pumps', 'ช่างติดตั้งปั๊มน้ำ'], autodoor: ['Automatic doors', 'ช่างติดตั้งประตูอัตโนมัติ'],
  roofing: ['Roofing', 'ช่างติดตั้งหลังคา'], glass: ['Glazier', 'ช่างติดตั้งกระจก'],
  // maid_skills that are not also trades
  cleaning: ['Cleaning', 'ทำความสะอาด'], cooking: ['Cooking', 'ทำอาหาร'],
  dishwashing: ['Dishwashing', 'ล้างจาน'], organizing: ['Organising', 'จัดของ'],
  packing: ['Packing', 'แพ็กของ'], ironing: ['Ironing', 'รีดผ้า'],
};

function teamLabel(key, lang) {
  const pair = TEAM_POSITION_LABELS[key];
  if (!pair) return key;
  return lang === 'th' ? pair[1] : pair[0];
}

function teamPositionOf(member, lang) {
  const key = member.trade || member.maid_type;
  return key ? teamLabel(key, lang) : (lang === 'th' ? 'ทีมงาน SVLM' : 'SVLM team');
}

// A person who has never been reviewed has no rating, and inventing 5.0 for them would be a lie
// that outranks people who actually earned their stars. New members say so instead.
function TeamRating({ member, lang, size = 14 }) {
  const rating = Number(member.avg_rating);
  if (!rating) {
    return (
      <span style={{ fontSize: 12, color: Ptm.faint, fontWeight: 600 }}>
        {lang === 'th' ? 'ยังไม่มีรีวิว' : 'No reviews yet'}
      </span>
    );
  }
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <Icon name="star" size={size} color={Ptm.star} fill={Ptm.star} sw={0} />
      <strong style={{ fontSize: size - 0.5, color: Ptm.ink, fontWeight: 800 }}>{rating.toFixed(1)}</strong>
      <span style={{ fontSize: size - 2, color: Ptm.faint }}>({Number(member.review_count) || 0})</span>
    </span>
  );
}

function TeamAvatar({ member, size }) {
  const [broken, setBroken] = React.useState(false);
  const initial = (member.nickname || member.name || '?').trim().charAt(0).toUpperCase();
  const shell = {
    width: size, height: size, borderRadius: 999, flexShrink: 0, overflow: 'hidden',
    background: Ptm.primarySoft, display: 'flex', alignItems: 'center', justifyContent: 'center',
    color: Ptm.primaryDk, fontWeight: 800, fontSize: size * 0.38,
  };
  if (!member.has_photo || broken) return <div style={shell}>{initial}</div>;
  return (
    <div style={shell}>
      <img src={`/api/candidates/${member.id}/photo`} alt="" onError={() => setBroken(true)}
        style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
    </div>
  );
}

function TeamGallery({ app }) {
  const L = app.lang;
  const [members, setMembers] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [group, setGroup] = React.useState('all');

  React.useEffect(() => {
    api('/candidates')
      .then(setMembers)
      .catch(e => { setErr(e.message); setMembers([]); });
  }, []);

  const groups = [
    { key: 'all', label: L === 'th' ? 'ทั้งหมด' : 'Everyone' },
    { key: 'cleaning', label: L === 'th' ? 'แม่บ้าน' : 'Housekeeping' },
    { key: 'tech', label: L === 'th' ? 'ช่าง' : 'Technicians' },
  ];
  const shown = (members || []).filter(m => {
    if (group === 'all') return true;
    if (group === 'cleaning') return m.role === 'cleaning';
    return m.role === 'repair' || m.role === 'aircon';
  });

  return (
    <div>
      <AppHeader onBack={app.back} title={L === 'th' ? 'ทีมงานของเรา' : 'Our team'}
        sub={L === 'th' ? 'เลือกคนที่คุณอยากให้มาทำงาน' : 'Choose who you would like to come'} />

      <div style={{ display: 'flex', gap: 8, padding: '0 20px 14px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {groups.map(g => (
          <button key={g.key} onClick={() => setGroup(g.key)} style={{
            border: `1.5px solid ${group === g.key ? Ptm.primary : Ptm.line}`,
            background: group === g.key ? Ptm.primarySoft : '#fff',
            color: group === g.key ? Ptm.primaryDk : Ptm.muted,
            borderRadius: Stm.pill, padding: '8px 16px', fontSize: 13.5, fontWeight: 700,
            fontFamily: 'inherit', cursor: 'pointer', whiteSpace: 'nowrap',
          }}>{g.label}</button>
        ))}
      </div>

      <div style={{ padding: '0 20px 40px' }}>
        {members === null && (
          <div style={{ textAlign: 'center', padding: '40px 0', color: Ptm.faint, fontSize: 14 }}>
            {L === 'th' ? 'กำลังโหลด…' : 'Loading…'}
          </div>
        )}
        {err && <p style={{ color: '#d23a3a', fontSize: 13 }}>{err}</p>}

        {members !== null && shown.length === 0 && !err && (
          <div style={{ textAlign: 'center', padding: '50px 0', color: Ptm.faint }}>
            <Icon name="user" size={42} color={Ptm.line} />
            <div style={{ marginTop: 12, fontSize: 14, fontWeight: 600 }}>
              {L === 'th' ? 'ยังไม่มีทีมงานให้เลือกในตอนนี้' : 'No team members listed yet'}
            </div>
            <div style={{ marginTop: 6, fontSize: 12.5 }}>
              {L === 'th' ? 'จองได้ตามปกติ เราจะจัดคนที่ว่างให้' : 'Book as usual and we will assign someone available'}
            </div>
          </div>
        )}

        <div style={{ display: 'grid', gap: 12 }}>
          {shown.map(m => (
            <button key={m.id} onClick={() => app.go('team-member', { member: m })} style={{
              display: 'flex', alignItems: 'center', gap: 14, width: '100%', textAlign: 'left',
              background: Ptm.card, border: `1px solid ${Ptm.line}`, borderRadius: Stm.card,
              padding: 14, cursor: 'pointer', fontFamily: 'inherit',
            }}>
              <TeamAvatar member={m} size={60} />
              <span style={{ minWidth: 0, flex: 1 }}>
                <span style={{ display: 'block', fontSize: 15.5, fontWeight: 800, color: Ptm.ink, overflowWrap: 'anywhere' }}>
                  {m.nickname || m.name}
                </span>
                <span style={{ display: 'block', fontSize: 13, color: Ptm.muted, margin: '2px 0 6px' }}>
                  {teamPositionOf(m, L)}
                </span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                  <TeamRating member={m} lang={L} />
                  {Number(m.total_jobs) > 0 && (
                    <span style={{ fontSize: 12, color: Ptm.faint }}>
                      {L === 'th' ? `${m.total_jobs} งาน` : `${m.total_jobs} jobs`}
                    </span>
                  )}
                  {Number(m.equipment_count) > 0 && (
                    <span style={{ fontSize: 12, color: Ptm.faint, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      <Icon name="wrench" size={13} color={Ptm.faint} />
                      {m.equipment_count}
                    </span>
                  )}
                </span>
              </span>
              <Icon name="chevR" size={18} color={Ptm.faint} />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function TeamMember({ app, params }) {
  const L = app.lang;
  const member = params.member;
  const [equipment, setEquipment] = React.useState([]);

  React.useEffect(() => {
    api(`/candidates/${member.id}/equipment`).then(setEquipment).catch(() => setEquipment([]));
  }, [member.id]);

  const skills = member.maid_skills || [];
  const chosen = app.requestedStaff && app.requestedStaff.id === member.id;

  return (
    <div>
      <AppHeader onBack={app.back} title={member.nickname || member.name} sub={teamPositionOf(member, L)} />

      <div style={{ padding: '0 20px 40px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 16, background: Ptm.card,
          border: `1px solid ${Ptm.line}`, borderRadius: Stm.card, padding: 18, marginBottom: 16,
        }}>
          <TeamAvatar member={member} size={84} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 800, color: Ptm.ink, overflowWrap: 'anywhere' }}>{member.nickname || member.name}</div>
            <div style={{ fontSize: 13.5, color: Ptm.muted, margin: '3px 0 8px' }}>{teamPositionOf(member, L)}</div>
            <TeamRating member={member} lang={L} size={16} />
            {Number(member.total_jobs) > 0 && (
              <div style={{ fontSize: 12.5, color: Ptm.faint, marginTop: 4 }}>
                {L === 'th' ? `ทำงานกับเราแล้ว ${member.total_jobs} งาน` : `${member.total_jobs} jobs completed`}
              </div>
            )}
          </div>
        </div>

        {skills.length > 0 && (
          <div style={{ marginBottom: 18 }}>
            <SectionHead title={L === 'th' ? 'รับงานประเภทนี้' : 'Takes on'} />
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {skills.map(s => (
                <span key={s} style={{
                  border: `1px solid ${Ptm.line}`, background: Ptm.navySoft, color: Ptm.navy,
                  borderRadius: Stm.pill, padding: '7px 14px', fontSize: 13, fontWeight: 600,
                }}>{teamLabel(s, L)}</span>
              ))}
            </div>
          </div>
        )}

        {equipment.length > 0 && (
          <div style={{ marginBottom: 18 }}>
            <SectionHead title={L === 'th' ? 'อุปกรณ์ที่นำมาด้วย' : 'Equipment they bring'} />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 12 }}>
              {equipment.map(photo => (
                <figure key={photo.id} style={{ margin: 0, border: `1px solid ${Ptm.line}`, borderRadius: Stm.tile, overflow: 'hidden', background: Ptm.card }}>
                  {/* contain, not cover: a ladder and a drill are not the same shape and a centre
                      crop would hide the tool the customer is trying to look at. */}
                  <img src={`/api/candidates/${member.id}/equipment/${photo.id}/photo`} alt={photo.caption || ''}
                    loading="lazy" style={{ width: '100%', height: 120, objectFit: 'contain', background: Ptm.bg, display: 'block' }} />
                  {photo.caption && (
                    <figcaption style={{ padding: '9px 11px', fontSize: 12.5, color: Ptm.ink, overflowWrap: 'anywhere' }}>
                      {photo.caption}
                    </figcaption>
                  )}
                </figure>
              ))}
            </div>
          </div>
        )}

        {/* Requesting someone narrows the job to them alone, so it can genuinely mean waiting
            longer — say so here rather than letting the customer discover it as a slow booking. */}
        <div style={{ background: Ptm.navySoft, borderRadius: Stm.tile, padding: '12px 14px', marginBottom: 14 }}>
          <div style={{ fontSize: 12.5, color: Ptm.navy, lineHeight: 1.6 }}>
            {L === 'th'
              ? 'เมื่อเลือกคนนี้ งานจะถูกส่งให้เขาคนเดียว ถ้าเขาไม่ว่างในวันที่คุณเลือก อาจต้องรอนานกว่าปกติ'
              : 'Choosing someone sends the job to them alone. If they are not free on your date, it may take longer to confirm.'}
          </div>
        </div>

        {chosen ? (
          <Btn variant="ghost" onClick={() => { app.setRequestedStaff(null); app.back(); }}>
            {L === 'th' ? 'ยกเลิกการเลือกคนนี้' : 'Clear this choice'}
          </Btn>
        ) : (
          <Btn onClick={() => {
            app.setRequestedStaff({ id: member.staff_id, recruitId: member.id, name: member.nickname || member.name, has_photo: member.has_photo });
            app.go('tab-services');
          }}>
            {L === 'th' ? 'เลือกคนนี้' : 'Choose this person'}
          </Btn>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TeamGallery, TeamMember, TeamRating, TeamAvatar, teamPositionOf, teamLabel });
