// RatingFlow.jsx — Rating screen for both professional (rates box) and owner (rates professional)

const MOCK_RESERVAS_RF = [
  { id: 'LKT-A1B2C3', box: 'Box Dental Premium', address: 'Av. Apoquindo 4501, piso 3', fecha: new Date(Date.now() + 1000*60*60*2), slot: 10, monto: 9350, status: 'confirmed', medico: 'Dr. Carlos Muñoz' },
  { id: 'LKT-D4E5F6', box: 'Box Kinesiología', address: 'Av. Providencia 2124, of. 502', fecha: new Date(Date.now() + 1000*60*60*30), slot: 14, monto: 6600, status: 'confirmed', medico: 'Dra. Ana Torres' },
  { id: 'LKT-G7H8I9', box: 'Box Psicología', address: 'Av. Irarrázaval 1890, of. 201', fecha: new Date(Date.now() - 1000*60*60*48), slot: 9, monto: 4950, status: 'completed', medico: 'Dr. Pedro Soto' },
];

// ── STAR RATING WIDGET ────────────────────────────────────────────────────────
const StarRating = ({ value, onChange, label }) => {
  const [hovered, setHovered] = React.useState(0);
  return (
    <div style={rfS.starRow}>
      <span style={rfS.starLabel}>{label}</span>
      <div style={rfS.stars}>
        {[1,2,3,4,5].map(n => (
          <span
            key={n}
            style={{...rfS.star, color: n <= (hovered || value) ? '#f39c12' : '#dee2e6'}}
            onMouseEnter={() => setHovered(n)}
            onMouseLeave={() => setHovered(0)}
            onClick={() => onChange(n)}
          >★</span>
        ))}
        <span style={rfS.starVal}>{value ? `${value}/5` : '—'}</span>
      </div>
    </div>
  );
};

// ── RATING FORM ───────────────────────────────────────────────────────────────
const RatingFlow = ({ userType = 'professional', reserva, onBack, onDone }) => {
  const res = reserva || MOCK_RESERVAS_RF[2];

  const profCategories = [
    { key: 'limpieza',       label: 'Limpieza' },
    { key: 'equipamiento',   label: 'Equipamiento' },
    { key: 'puntualidad',    label: 'Puntualidad de acceso' },
    { key: 'precio',         label: 'Relación precio / calidad' },
  ];
  const ownerCategories = [
    { key: 'puntualidad',    label: 'Puntualidad' },
    { key: 'cuidado',        label: 'Cuidado del box' },
    { key: 'comunicacion',   label: 'Comunicación' },
    { key: 'volveria',       label: 'Volvería a arrendar' },
  ];

  const categories = userType === 'professional' ? profCategories : ownerCategories;
  const initRatings = Object.fromEntries(categories.map(c => [c.key, 0]));

  const [ratings, setRatings] = React.useState(initRatings);
  const [comment, setComment] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const allFilled = Object.values(ratings).every(v => v > 0);
  const avg = allFilled
    ? (Object.values(ratings).reduce((a,b) => a+b, 0) / categories.length).toFixed(1)
    : null;

  const handleSubmit = () => {
    if (!allFilled) return;
    setSubmitting(true);
    setTimeout(() => { setSubmitting(false); setSubmitted(true); }, 1400);
  };

  if (submitted) {
    return (
      <div style={rfS.page}>
        <div style={rfS.topBar}>
          <button style={rfS.backBtn} onClick={onDone || onBack}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
          </button>
          <div style={rfS.topBarTitle}>Calificación enviada</div>
          <div style={{width:36}}></div>
        </div>
        <div style={rfS.thanksCont}>
          <div style={rfS.thanksIcon}>✓</div>
          <h2 style={rfS.thanksTitle}>¡Gracias por tu calificación!</h2>
          <p style={rfS.thanksSub}>Tu opinión ayuda a mejorar la comunidad Lokat.</p>
          <div style={rfS.avgCard}>
            <div style={rfS.avgStars}>
              {[1,2,3,4,5].map(n => (
                <span key={n} style={{...rfS.avgStar, color: n <= Math.round(parseFloat(avg)) ? '#f39c12' : '#dee2e6'}}>★</span>
              ))}
            </div>
            <div style={rfS.avgNum}>{avg} / 5</div>
            <div style={rfS.avgLabel}>Promedio general</div>
          </div>
          <div style={rfS.breakdownCard}>
            {categories.map(c => (
              <div key={c.key} style={rfS.breakdownRow}>
                <span style={rfS.breakdownLabel}>{c.label}</span>
                <div style={rfS.breakdownBar}>
                  <div style={{...rfS.breakdownFill, width: `${(ratings[c.key]/5)*100}%`}}></div>
                </div>
                <span style={rfS.breakdownVal}>{ratings[c.key]}</span>
              </div>
            ))}
          </div>
          <button style={rfS.doneBtn} onClick={onDone || onBack}>Volver</button>
        </div>
      </div>
    );
  }

  return (
    <div style={rfS.page}>
      <div style={rfS.topBar}>
        <button style={rfS.backBtn} onClick={onBack}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        </button>
        <div style={rfS.topBarTitle}>
          {userType === 'professional' ? 'Califica el box' : 'Califica al profesional'}
        </div>
        <div style={{width:36}}></div>
      </div>

      <div style={rfS.container}>
        {/* Summary card */}
        <div style={rfS.summaryCard}>
          <div style={rfS.summaryIconWrap}>
            {userType === 'professional'
              ? <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#0984e3" strokeWidth="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
              : <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#0984e3" strokeWidth="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
            }
          </div>
          <div>
            <div style={rfS.summaryTitle}>
              {userType === 'professional' ? res.box : res.medico}
            </div>
            <div style={rfS.summaryMeta}>
              {userType === 'professional' ? res.address : res.box}
              {' · '}Reserva {res.id}
            </div>
          </div>
        </div>

        {/* Rating card */}
        <div style={rfS.ratingCard}>
          <div style={rfS.ratingCardTitle}>
            {userType === 'professional' ? '¿Cómo fue tu experiencia en el box?' : '¿Cómo fue el profesional?'}
          </div>
          {categories.map(c => (
            <StarRating
              key={c.key}
              label={c.label}
              value={ratings[c.key]}
              onChange={v => setRatings(p => ({...p, [c.key]: v}))}
            />
          ))}
        </div>

        {/* Comment */}
        <div style={rfS.commentCard}>
          <label style={rfS.commentLabel}>Comentario (opcional)</label>
          <textarea
            style={rfS.commentArea}
            placeholder={userType === 'professional'
              ? 'Cuéntanos más sobre el estado del box, equipamiento, etc.'
              : 'Cuéntanos sobre la puntualidad, trato y cuidado del box...'}
            value={comment}
            onChange={e => setComment(e.target.value)}
            rows={4}
          />
        </div>

        {/* Submit */}
        <button
          style={{...rfS.submitBtn, opacity: allFilled ? 1 : 0.45, cursor: allFilled ? 'pointer' : 'not-allowed'}}
          onClick={handleSubmit}
          disabled={!allFilled || submitting}
        >
          {submitting
            ? <span style={{display:'flex',alignItems:'center',gap:8,justifyContent:'center'}}>
                <span style={rfS.spinner}></span>Enviando...
              </span>
            : 'Enviar calificación'}
        </button>
        {!allFilled && <div style={rfS.hint}>Completa todas las categorías para enviar</div>}
      </div>
    </div>
  );
};

// ── STYLES ────────────────────────────────────────────────────────────────────
const rfS = {
  page: { minHeight:'100vh', background:'#e4e9f0', fontFamily:"'Helvetica Neue',Helvetica,Arial,sans-serif", color:'#2D3436' },
  topBar: { background:'#fff', borderBottom:'1px solid #e9ecef', display:'flex', alignItems:'center', gap:12, padding:'0 16px', height:60, position:'sticky', top:0, zIndex:50 },
  backBtn: { width:36, height:36, borderRadius:8, border:'1px solid #e9ecef', background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 },
  topBarTitle: { flex:1, fontSize:16, fontWeight:700 },
  container: { maxWidth:560, margin:'0 auto', padding:'24px 16px', display:'flex', flexDirection:'column', gap:16 },
  summaryCard: { background:'#fff', borderRadius:16, padding:16, display:'flex', alignItems:'center', gap:14, border:'1px solid #e9ecef' },
  summaryIconWrap: { width:44, height:44, background:'#e3f0fc', borderRadius:12, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 },
  summaryTitle: { fontSize:15, fontWeight:700 },
  summaryMeta: { fontSize:12, color:'#636e72', marginTop:2 },
  ratingCard: { background:'#fff', borderRadius:16, padding:24, border:'1px solid #e9ecef', boxShadow:'0 4px 16px rgba(0,0,0,0.05)' },
  ratingCardTitle: { fontSize:14, fontWeight:600, color:'#636e72', marginBottom:20 },
  starRow: { display:'flex', alignItems:'center', justifyContent:'space-between', paddingBottom:14, marginBottom:14, borderBottom:'1px solid #f0f4f8' },
  starLabel: { fontSize:14, fontWeight:500, color:'#2D3436', flex:1 },
  stars: { display:'flex', alignItems:'center', gap:4 },
  star: { fontSize:28, cursor:'pointer', transition:'color 0.1s', userSelect:'none', lineHeight:1 },
  starVal: { fontSize:12, color:'#adb5bd', marginLeft:6, minWidth:28 },
  commentCard: { background:'#fff', borderRadius:16, padding:20, border:'1px solid #e9ecef' },
  commentLabel: { display:'block', fontSize:13, fontWeight:600, marginBottom:10 },
  commentArea: { width:'100%', border:'1.5px solid #dee2e6', borderRadius:10, padding:'11px 14px', fontSize:14, color:'#2D3436', fontFamily:"'Helvetica Neue',Helvetica,Arial,sans-serif", resize:'vertical', outline:'none', boxSizing:'border-box', minHeight:90 },
  submitBtn: { width:'100%', background:'#0984e3', color:'#fff', border:'none', borderRadius:12, padding:15, fontSize:15, fontWeight:700, fontFamily:'inherit', transition:'opacity 0.2s' },
  hint: { textAlign:'center', fontSize:12, color:'#adb5bd', marginTop:-8 },
  spinner: { width:16, height:16, border:'2px solid rgba(255,255,255,0.35)', borderTop:'2px solid #fff', borderRadius:'50%', animation:'spin 0.8s linear infinite', display:'inline-block' },
  // Thanks screen
  thanksCont: { maxWidth:480, margin:'0 auto', padding:'48px 20px', textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center', gap:16 },
  thanksIcon: { width:76, height:76, background:'#00b894', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontSize:34, fontWeight:800 },
  thanksTitle: { fontSize:24, fontWeight:800, margin:0 },
  thanksSub: { fontSize:14, color:'#636e72', margin:0 },
  avgCard: { background:'#fff', borderRadius:16, padding:'20px 32px', border:'1px solid #e9ecef', display:'flex', flexDirection:'column', alignItems:'center', gap:6, width:'100%' },
  avgStars: { display:'flex', gap:4 },
  avgStar: { fontSize:32 },
  avgNum: { fontSize:36, fontWeight:800, color:'#2D3436', lineHeight:1 },
  avgLabel: { fontSize:12, color:'#adb5bd' },
  breakdownCard: { background:'#fff', borderRadius:16, padding:20, border:'1px solid #e9ecef', width:'100%', display:'flex', flexDirection:'column', gap:12 },
  breakdownRow: { display:'flex', alignItems:'center', gap:10 },
  breakdownLabel: { fontSize:13, color:'#636e72', width:160, textAlign:'left', flexShrink:0 },
  breakdownBar: { flex:1, height:6, background:'#e9ecef', borderRadius:3, overflow:'hidden' },
  breakdownFill: { height:'100%', background:'#f39c12', borderRadius:3, transition:'width 0.5s ease' },
  breakdownVal: { fontSize:13, fontWeight:700, width:18, textAlign:'right', flexShrink:0 },
  doneBtn: { background:'#0984e3', color:'#fff', border:'none', borderRadius:12, padding:'13px 40px', fontSize:15, fontWeight:700, cursor:'pointer', fontFamily:'inherit' },
};

window.RatingFlow = RatingFlow;
