// feedback.jsx — Website feedback / improvement suggestion modal
// Used by both student profile and teacher profile

const { useState: useStateF } = React;

function FeedbackModal({ lang, onClose }) {
  const L = lang === 'th' ? {
    title: 'ติชม / แก้ไขเว็บไซต์',
    sub: 'ความคิดเห็นของคุณช่วยให้ Bodin plus ดีขึ้น',
    type: 'ประเภท',
    types: [
      { id: 'bug',     label: 'พบปัญหา / Bug',  icon: 'bolt',    tint: 'oklch(0.62 0.22 25)' },
      { id: 'idea',    label: 'ข้อเสนอแนะ',     icon: 'sparkle', tint: 'var(--bp-violet)'    },
      { id: 'praise',  label: 'ชื่นชม',          icon: 'heart',   tint: 'oklch(0.62 0.18 0)'  },
      { id: 'other',   label: 'อื่นๆ',           icon: 'list',    tint: 'var(--bp-blue)'      },
    ],
    rating: 'ให้คะแนนเว็บไซต์',
    ratingHint: 'ให้คะแนนความพึงพอใจของคุณต่อ Bodin plus',
    detail: 'รายละเอียด',
    detailPh: 'อธิบายปัญหาที่พบ หรือสิ่งที่อยากให้ปรับปรุง...',
    page: 'หน้าที่เกี่ยวข้อง (ไม่บังคับ)',
    pagePh: 'เช่น หน้าโปรไฟล์, รายการแจ้ง, ฯลฯ',
    contact: 'ขอให้ติดต่อกลับ',
    contactSub: 'ทีมงานจะติดต่อกลับทางอีเมล',
    cancel: 'ยกเลิก',
    submit: 'ส่งความคิดเห็น',
    submitting: 'กำลังส่ง...',
    successTitle: 'ขอบคุณสำหรับความคิดเห็น!',
    successSub: 'ทีมงานได้รับข้อความของคุณแล้ว และจะนำไปปรับปรุง',
    close: 'ปิด',
    requiredErr: 'กรุณาเลือกประเภทและกรอกรายละเอียด',
    ratingLabels: ['แย่มาก', 'ไม่ค่อยดี', 'พอใช้', 'ดี', 'ดีมาก'],
  } : {
    title: 'Feedback / Suggest improvement',
    sub: 'Your feedback helps make Bodin plus better',
    type: 'Type',
    types: [
      { id: 'bug',     label: 'Bug report',  icon: 'bolt',    tint: 'oklch(0.62 0.22 25)' },
      { id: 'idea',    label: 'Suggestion',  icon: 'sparkle', tint: 'var(--bp-violet)'    },
      { id: 'praise',  label: 'Praise',      icon: 'heart',   tint: 'oklch(0.62 0.18 0)'  },
      { id: 'other',   label: 'Other',       icon: 'list',    tint: 'var(--bp-blue)'      },
    ],
    rating: 'Rate the website',
    ratingHint: 'How satisfied are you with Bodin plus?',
    detail: 'Details',
    detailPh: 'Describe the issue or what you\'d like to see improved…',
    page: 'Related page (optional)',
    pagePh: 'e.g. Profile, Reports list…',
    contact: 'Request follow-up',
    contactSub: 'Our team will contact you via email',
    cancel: 'Cancel',
    submit: 'Send feedback',
    submitting: 'Sending…',
    successTitle: 'Thanks for your feedback!',
    successSub: 'Our team has received your message and will improve.',
    close: 'Close',
    requiredErr: 'Please pick a type and add details',
    ratingLabels: ['Very bad', 'Bad', 'OK', 'Good', 'Excellent'],
  };

  const [type, setType] = useStateF(null);
  const [rating, setRating] = useStateF(0);
  const [hoverR, setHoverR] = useStateF(0);
  const [detail, setDetail] = useStateF('');
  const [page, setPage] = useStateF('');
  const [contact, setContact] = useStateF(false);
  const [submitting, setSubmitting] = useStateF(false);
  const [done, setDone] = useStateF(false);
  const [err, setErr] = useStateF('');

  function submit(e) {
    e?.preventDefault?.();
    if (!type || !detail.trim()) { setErr(L.requiredErr); return; }
    setErr('');
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setDone(true);
    }, 700);
  }

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset: 0,
      background:'rgba(20, 14, 60, 0.42)',
      backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)',
      display:'flex', alignItems:'center', justifyContent:'center',
      zIndex: 200, padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background:'var(--bp-surface)',
        borderRadius: 20,
        width:'100%', maxWidth: 480,
        maxHeight: 'calc(100vh - 40px)',
        boxShadow:'var(--bp-shadow-lg)',
        border:'1px solid var(--bp-line)',
        display:'flex', flexDirection:'column',
        overflow:'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding:'18px 22px 16px',
          borderBottom:'1px solid var(--bp-line)',
          display:'flex', alignItems:'flex-start', gap: 12,
          background:'var(--bp-grad-soft)',
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 11,
            background:'var(--bp-grad)', color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center',
            boxShadow:'0 6px 14px rgba(80,50,180,0.25)', flexShrink: 0,
          }}><Icon name="sparkle" size={20} strokeWidth={1.8}/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700, color:'var(--bp-ink)', letterSpacing:'-0.01em' }}>{L.title}</div>
            <div style={{ fontSize: 12, color:'var(--bp-ink-2)', marginTop: 2, lineHeight: 1.4 }}>{L.sub}</div>
          </div>
          <button onClick={onClose} style={{
            appearance:'none', border:0, cursor:'pointer',
            background:'rgba(45,30,110,0.06)',
            width: 30, height: 30, borderRadius: 8, color:'var(--bp-ink-2)',
            display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
          }}><Icon name="close" size={13}/></button>
        </div>

        {!done ? (
          <>
            {/* Body */}
            <div style={{ overflow:'auto', padding:'18px 22px', flex: 1, display:'flex', flexDirection:'column', gap: 16 }}>
              {/* Type picker */}
              <div>
                <FbLabel>{L.type} <Required/></FbLabel>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8 }}>
                  {L.types.map(ty => {
                    const active = type === ty.id;
                    return (
                      <button key={ty.id} onClick={() => setType(ty.id)} style={{
                        appearance:'none', cursor:'pointer',
                        padding:'10px 12px', borderRadius: 11,
                        border: active ? `1.5px solid ${ty.tint}` : '1px solid var(--bp-line)',
                        background: active ? ty.tint + '12' : 'var(--bp-surface)',
                        display:'flex', alignItems:'center', gap: 9,
                        textAlign:'left', fontFamily:'inherit',
                        transition:'border-color .12s ease, background .12s ease',
                      }}>
                        <span style={{
                          width: 28, height: 28, borderRadius: 8,
                          background: ty.tint, color:'#fff',
                          display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
                        }}><Icon name={ty.icon} size={14} strokeWidth={2}/></span>
                        <span style={{
                          fontSize: 12.5, fontWeight: 500, color:'var(--bp-ink)',
                        }}>{ty.label}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Rating */}
              <div>
                <FbLabel>{L.rating}</FbLabel>
                <div style={{
                  padding:'14px 16px', borderRadius: 12,
                  background:'var(--bp-soft)', border:'1px solid var(--bp-line)',
                }}>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap: 12 }}>
                    <div style={{ display:'flex', gap: 4 }}>
                      {[1,2,3,4,5].map(n => {
                        const filled = (hoverR || rating) >= n;
                        return (
                          <button key={n}
                            onClick={() => setRating(n)}
                            onMouseEnter={() => setHoverR(n)}
                            onMouseLeave={() => setHoverR(0)}
                            style={{
                              appearance:'none', border:0, background:'transparent', cursor:'pointer',
                              padding: 2, transition:'transform .12s ease',
                              transform: filled ? 'scale(1.08)' : 'scale(1)',
                            }}>
                            <Star filled={filled}/>
                          </button>
                        );
                      })}
                    </div>
                    <div style={{
                      fontSize: 12, fontWeight: 600,
                      color: (hoverR || rating) ? 'var(--bp-violet)' : 'var(--bp-ink-3)',
                      minWidth: 70, textAlign:'right',
                    }}>
                      {(hoverR || rating) ? L.ratingLabels[(hoverR || rating) - 1] : L.ratingHint.slice(0, 20)}
                    </div>
                  </div>
                </div>
              </div>

              {/* Detail */}
              <div>
                <FbLabel>{L.detail} <Required/></FbLabel>
                <textarea value={detail} onChange={e => setDetail(e.target.value)}
                  placeholder={L.detailPh} rows={4} style={fbInputStyle('textarea')}/>
                <div style={{ display:'flex', justifyContent:'flex-end', marginTop: 4 }}>
                  <span style={{ fontSize: 10.5, color:'var(--bp-ink-3)' }}>{detail.length} / 500</span>
                </div>
              </div>

              {/* Page hint */}
              <div>
                <FbLabel>{L.page}</FbLabel>
                <input value={page} onChange={e => setPage(e.target.value)}
                  placeholder={L.pagePh} style={fbInputStyle('input')}/>
              </div>

              {/* Contact toggle */}
              <label style={{
                display:'flex', alignItems:'center', gap: 12,
                padding:'12px 14px', borderRadius: 11,
                background:'var(--bp-soft)', border:'1px solid var(--bp-line)',
                cursor:'pointer',
              }}>
                <span onClick={(e) => { e.preventDefault(); setContact(c => !c); }} style={{
                  width: 18, height: 18, borderRadius: 5,
                  border: contact ? '0' : '1.5px solid var(--bp-line-2)',
                  background: contact ? 'var(--bp-grad)' : 'var(--bp-surface)',
                  display:'inline-flex', alignItems:'center', justifyContent:'center', color:'#fff',
                  transition:'background .15s ease', flexShrink: 0,
                }}>
                  {contact && <Icon name="check" size={12} strokeWidth={2.6}/>}
                </span>
                <input type="checkbox" checked={contact} onChange={e => setContact(e.target.checked)} style={{ display:'none' }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color:'var(--bp-ink)' }}>{L.contact}</div>
                  <div style={{ fontSize: 11, color:'var(--bp-ink-3)', marginTop: 1 }}>{L.contactSub}</div>
                </div>
              </label>

              {err && (
                <div style={{
                  fontSize: 12, color:'oklch(0.45 0.20 25)',
                  background:'oklch(0.96 0.05 25)', padding:'8px 12px', borderRadius: 10,
                  display:'flex', alignItems:'center', gap: 8,
                }}>
                  <Icon name="bolt" size={13}/> {err}
                </div>
              )}
            </div>

            {/* Footer actions */}
            <div style={{
              padding:'14px 22px', borderTop:'1px solid var(--bp-line)',
              display:'flex', gap: 10, justifyContent:'flex-end',
              background:'var(--bp-surface)',
            }}>
              <button onClick={onClose} style={{
                appearance:'none', cursor:'pointer',
                padding:'10px 18px', borderRadius: 11,
                background:'var(--bp-surface)', border:'1px solid var(--bp-line)',
                color:'var(--bp-ink-2)', fontFamily:'inherit',
                fontSize: 13, fontWeight: 500,
              }}>{L.cancel}</button>
              <button onClick={submit} disabled={submitting} style={{
                appearance:'none', border:0, cursor: submitting ? 'wait' : 'pointer',
                padding:'10px 22px', borderRadius: 11,
                background:'var(--bp-grad)', color:'#fff',
                fontSize: 13, fontWeight: 600, fontFamily:'inherit',
                boxShadow:'0 8px 18px rgba(80,50,180,0.25)',
                display:'inline-flex', alignItems:'center', gap: 6,
                opacity: submitting ? 0.85 : 1,
              }}>
                {submitting
                  ? <><Spinner/> {L.submitting}</>
                  : <><Icon name="arrow_r" size={14}/> {L.submit}</>}
              </button>
            </div>
          </>
        ) : (
          // Success state
          <div style={{ padding:'40px 30px 32px', textAlign:'center' }}>
            <div style={{
              width: 80, height: 80, borderRadius:'50%',
              background:'var(--bp-grad)', color:'#fff',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              boxShadow:'0 14px 32px rgba(80,50,180,0.30)',
              animation:'bp-pop 0.5s cubic-bezier(.2,1.2,.4,1)',
            }}><Icon name="check" size={40} strokeWidth={2.4}/></div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 18, color:'var(--bp-ink)' }}>{L.successTitle}</div>
            <div style={{ fontSize: 13, color:'var(--bp-ink-2)', marginTop: 6, lineHeight: 1.5, maxWidth: 320, marginLeft:'auto', marginRight:'auto' }}>{L.successSub}</div>
            <button onClick={onClose} style={{
              marginTop: 22, appearance:'none', border:0, cursor:'pointer',
              padding:'10px 28px', borderRadius: 11,
              background:'var(--bp-grad)', color:'#fff',
              fontSize: 13, fontWeight: 600, fontFamily:'inherit',
              boxShadow:'0 8px 18px rgba(80,50,180,0.25)',
            }}>{L.close}</button>
          </div>
        )}
      </div>
    </div>
  );
}

function FbLabel({ children }) {
  return (
    <div style={{ fontSize: 12, fontWeight: 600, color:'var(--bp-ink-2)', marginBottom: 8 }}>{children}</div>
  );
}

function Required() {
  return <span style={{ color:'oklch(0.60 0.22 25)' }}>*</span>;
}

function fbInputStyle(kind) {
  return {
    width:'100%', appearance:'none',
    padding: kind === 'textarea' ? '11px 13px' : '10px 13px',
    borderRadius: 11, border:'1px solid var(--bp-line)',
    background:'var(--bp-surface)', color:'var(--bp-ink)',
    fontFamily:'inherit', fontSize: 13, outline:'none',
    resize: kind === 'textarea' ? 'vertical' : undefined,
    minHeight: kind === 'textarea' ? 96 : undefined,
    boxSizing: 'border-box',
  };
}

function Star({ filled }) {
  return (
    <svg width="26" height="26" viewBox="0 0 24 24" fill={filled ? 'url(#bp-star-grad)' : 'none'} stroke={filled ? 'none' : 'var(--bp-line-2)'} strokeWidth="1.5">
      <defs>
        <linearGradient id="bp-star-grad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%"   stopColor="oklch(0.62 0.20 295)"/>
          <stop offset="100%" stopColor="oklch(0.68 0.20 325)"/>
        </linearGradient>
      </defs>
      <path d="M12 2l3 6.5 7 1-5 4.8 1.3 7L12 17.7 5.7 21.3 7 14.3 2 9.5l7-1z" strokeLinejoin="round"/>
    </svg>
  );
}

Object.assign(window, { FeedbackModal });
