/* ============================================================
   SVLM — Handyman Hub (category landing for group='handyman' services)
   and Review submission. Ported from public/index.html's
   showReviewForm()/submitReview() (same real POST /reviews, same 5
   criteria) — Handyman Hub itself has no 1:1 vanilla-app equivalent
   (that app just filters the Services tab by group), so this is a
   richer landing screen built fresh in the same visual language,
   reachable from Home's Handyman category tile.
   ============================================================ */
const Phr = window.PALETTE;

function HandymanHub({ app }) {
  const list = app.services.filter(s => s.group === 'handyman');
  const cats = [...new Set(list.map(s => s.cat).filter(Boolean))];

  return (
    <div>
      <AppHeader onBack={app.back} title={app.t('cat_handyman') || 'Handyman'} />
      <div style={{ padding: '0 20px 8px' }}>
        <div style={{ borderRadius: 20, padding: 20, background: `linear-gradient(135deg, ${Phr.navy}, #8a4a10)`, color: '#fff', marginBottom: 20 }}>
          <div style={{ fontSize: 17, fontWeight: 800 }}>{app.lang === 'th' ? 'ช่างมืออาชีพ พร้อมช่วยคุณ' : 'Skilled technicians, ready to help'}</div>
          <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.8)', marginTop: 4 }}>{app.lang === 'th' ? 'ซ่อมไฟ ประปา แอร์ และงานช่างทุกประเภท' : 'Electrical, plumbing, aircon, and every trade in between'}</div>
        </div>
      </div>
      <div style={{ padding: '0 20px' }}>
        <SectionHead title={app.lang === 'th' ? 'บริการช่างทั้งหมด' : 'All handyman services'} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {list.map(s => <ServiceCard key={s.id} app={app} s={s} />)}
        </div>
        {list.length === 0 && (
          <div style={{ textAlign: 'center', padding: '50px 0', color: Phr.faint }}>
            <Icon name="wrench" size={42} color={Phr.line} />
            <div style={{ marginTop: 12, fontSize: 14, fontWeight: 600 }}>{app.lang === 'th' ? 'ยังไม่มีบริการช่างในหมวดนี้' : 'No handyman services yet'}</div>
          </div>
        )}
      </div>
    </div>
  );
}

const REVIEW_CRITERIA = ['punctuality', 'politeness', 'skill', 'equipment', 'kindness'];

function ReviewScreen({ app, params }) {
  const { bookingId, serviceName } = params;
  const [scores, setScores] = React.useState({ punctuality: 5, politeness: 5, skill: 5, equipment: 5, kindness: 5 });
  const [err, setErr] = React.useState('');
  const [done, setDone] = React.useState(false);

  const submit = async () => {
    setErr('');
    try {
      await api('/reviews', { method: 'POST', body: JSON.stringify({ booking_id: bookingId, ...scores }) });
      setDone(true);
    } catch (e) { setErr(e.message); }
  };

  if (done) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24, textAlign: 'center' }}>
        <div style={{ width: 76, height: 76, borderRadius: 99, background: Phr.mintSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
          <Icon name="star" size={36} color={Phr.mint} fill={Phr.mint} sw={0} />
        </div>
        <h2 style={{ fontSize: 19, fontWeight: 800, color: Phr.ink, margin: '0 0 20px' }}>{t('customer', 'thanks_review') || 'Thanks for your review!'}</h2>
        <Btn style={{ maxWidth: 260 }} onClick={() => app.go('bookings')}>{t('customer', 'my_bookings_title') || 'My bookings'}</Btn>
      </div>
    );
  }

  return (
    <div>
      <AppHeader onBack={app.back} title={t('customer', 'leave_review') || 'Leave a review'} sub={serviceName} />
      <div style={{ padding: '0 20px 40px' }}>
        {REVIEW_CRITERIA.map(c => (
          <Field key={c} label={t('customer', `crit_${c}`) || c}>
            <div style={{ display: 'flex', gap: 8 }}>
              {[1, 2, 3, 4, 5].map(n => (
                <button key={n} onClick={() => setScores(s => ({ ...s, [c]: n }))} style={{ flex: 1, height: 42, borderRadius: 12, border: `1.5px solid ${scores[c] >= n ? Phr.primary : Phr.line}`, background: scores[c] >= n ? Phr.tintBlue : '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="star" size={17} color={scores[c] >= n ? Phr.primary : Phr.line} fill={scores[c] >= n ? Phr.primary : 'none'} sw={scores[c] >= n ? 0 : 1.8} />
                </button>
              ))}
            </div>
          </Field>
        ))}
        {err && <p style={{ color: '#d23a3a', fontSize: 13, marginBottom: 10 }}>{err}</p>}
        <Btn onClick={submit}>{t('customer', 'submit_review') || 'Submit review'}</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { HandymanHub, ReviewScreen });
