const { useState } = React;

const FAQS = [
  {
    category: "General & Curriculum",
    items: [
      { q: "How do I progress to the next module?", a: "Modules in the Edstutia LMS are sequential. You must watch the current video and complete its associated activities (e.g., uploading a video or completing a survey) before the next module automatically unlocks." },
      { q: "Where can I find my pre-course surveys?", a: "Pre-course surveys are located at the beginning of Module 1. You must complete these before accessing the core video materials." },
      { q: "Can I download the learning materials?", a: "Yes, you can download any provided PDFs or resources from the 'Resources' tab inside your lessons. Some activities may ask you to upload modified versions of these documents." }
    ]
  },
  {
    category: "Technical & VR Support",
    items: [
      { q: "My VR headset isn't connecting to the platform.", a: "Ensure your headset is on the same Wi-Fi network as your device. Try restarting the Edstutia application on the headset and verifying your pairing code on the dashboard." },
      { q: "I'm having trouble uploading a video.", a: "Our platform accepts standard video formats (MP4, MOV, WEBM) up to 500MB. Ensure your browser has permission to access your webcam if you are recording directly. If the upload hangs, check your network connection and try again." },
      { q: "The AI Persona isn't responding in the simulation.", a: "If an AI persona becomes unresponsive, please refresh the page to restart the session. Your progress in the conversational tree will be saved automatically." }
    ]
  }
];

function SupportPage() {
  const [search, setSearch] = useState('');
  const [openFaq, setOpenFaq] = useState(null);
  
  const [ticketSubject, setTicketSubject] = useState('');
  const [ticketMessage, setTicketMessage] = useState('');
  const [ticketCategory, setTicketCategory] = useState('Technical Issue');
  const [ticketStatus, setTicketStatus] = useState(null); // 'loading', 'success'

  const toggleFaq = (idx) => {
    setOpenFaq(openFaq === idx ? null : idx);
  };

  const handleTicketSubmit = async (e) => {
    e.preventDefault();
    setTicketStatus('loading');

    const learner = window.EDSTUTIA?.learner || {};

    if (window.supabaseClient) {
      const { error } = await window.supabaseClient.from('support_tickets').insert({
        user_id: window.ME_UUID || null,
        user_name: learner.name || null,
        user_email: learner.email || null,
        category: ticketCategory,
        subject: ticketSubject,
        message: ticketMessage,
        status: 'open'
      });
      if (error) {
        setTicketStatus(null);
        alert('Could not submit ticket: ' + error.message);
        return;
      }
    }

    setTicketStatus('success');
    setTicketSubject('');
    setTicketMessage('');
    setTimeout(() => setTicketStatus(null), 6000);
  };

  return (
    <div className="page enter">
      <span className="eyebrow">Assistance</span>
      <h1 style={{ fontSize: 34, marginTop: 6 }}>Help & Support</h1>
      <p className="muted" style={{ fontSize: 18, marginTop: 6, maxWidth: 620 }}>
        Troubleshoot technical issues, review curriculum FAQs, or contact our support team.
      </p>
      
      <div className="grid" style={{ gridTemplateColumns: '1fr 340px', gap: 32, alignItems: 'start', marginTop: 32 }}>
        
        {/* Main Content Area */}
        <div className="col gap-40">
          
          {/* Quick Links / Categories */}
          <div>
            <h2 style={{ fontSize: 22, marginBottom: 20 }}>Browse by Topic</h2>
            <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16 }}>
              <div className="card card-pad card-hover" style={{ cursor: 'pointer' }}>
                <div style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--lime-soft)', color: 'var(--lime-strong)', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
                  <Icon name="users" size={20} />
                </div>
                <h3 style={{ fontSize: 17, marginBottom: 4 }}>Account & Profile</h3>
                <p className="muted" style={{ fontSize: 14, margin: 0 }}>Login, settings, and profile info.</p>
              </div>
              
              <div className="card card-pad card-hover" style={{ cursor: 'pointer' }}>
                <div style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--lime-soft)', color: 'var(--lime-strong)', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
                  <Icon name="headset" size={20} />
                </div>
                <h3 style={{ fontSize: 17, marginBottom: 4 }}>VR Support</h3>
                <p className="muted" style={{ fontSize: 14, margin: 0 }}>Headset setup and troubleshooting.</p>
              </div>
              
              <div className="card card-pad card-hover" style={{ cursor: 'pointer' }}>
                <div style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--lime-soft)', color: 'var(--lime-strong)', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
                  <Icon name="book" size={20} />
                </div>
                <h3 style={{ fontSize: 17, marginBottom: 4 }}>Curriculum</h3>
                <p className="muted" style={{ fontSize: 14, margin: 0 }}>Modules, videos, and assignments.</p>
              </div>
            </div>
          </div>
          
          {/* FAQs */}
          <div>
            <h2 style={{ fontSize: 22, marginBottom: 20 }}>Frequently Asked Questions</h2>
            <div className="col gap-24">
              {FAQS.map((category, catIdx) => (
                <div key={catIdx}>
                  <h3 style={{ fontSize: 14, textTransform: 'uppercase', letterSpacing: 1, color: 'var(--text-muted)', marginBottom: 12 }}>
                    {category.category}
                  </h3>
                  <div className="card col" style={{ padding: 0, overflow: 'hidden' }}>
                    {category.items.map((item, itemIdx) => {
                      const globalIdx = catIdx + "-" + itemIdx;
                      const isOpen = openFaq === globalIdx;
                      return (
                        <div key={itemIdx} style={{ borderBottom: itemIdx < category.items.length - 1 ? '1px solid var(--border)' : 'none' }}>
                          <button 
                            style={{ 
                              width: '100%', padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                              background: isOpen ? 'var(--bg-2)' : 'transparent', border: 'none', textAlign: 'left', cursor: 'pointer',
                              fontSize: 16, fontWeight: 600, color: 'var(--text)', transition: 'background .2s'
                            }}
                            onClick={() => toggleFaq(globalIdx)}
                          >
                            <span>{item.q}</span>
                            <span style={{ transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s', color: 'var(--text-muted)' }}>
                              <Icon name="chevdown" size={20} />
                            </span>
                          </button>
                          {isOpen && (
                            <div style={{ padding: '0 20px 20px', fontSize: 15, lineHeight: 1.6, color: 'var(--text-muted)', background: 'var(--bg-2)' }}>
                              {item.a}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
          
        </div>
        
        {/* Sidebar Area */}
        <div className="col gap-24">
          
          {/* System Status */}
          <div className="card" style={{ padding: 20 }}>
            <div className="row gap-12" style={{ alignItems: 'center', marginBottom: 12 }}>
              <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#34c759', boxShadow: '0 0 8px rgba(52,199,89,0.6)' }} />
              <h3 style={{ fontSize: 16, margin: 0 }}>System Status</h3>
            </div>
            <p className="muted" style={{ fontSize: 14, margin: 0 }}>All services are fully operational. No current outages reported.</p>
          </div>
          
          {/* Contact Form */}
          <div className="card" style={{ padding: 24 }}>
            <h3 style={{ fontSize: 18, marginBottom: 8 }}>Still need help?</h3>
            <p className="muted" style={{ fontSize: 14, marginBottom: 20 }}>Submit a ticket to our support team and we'll get back to you within 24 hours.</p>
            
            {ticketStatus === 'success' ? (
              <div style={{ padding: 24, textAlign: 'center', background: 'var(--lime-soft)', borderRadius: 8, color: 'var(--lime-strong)' }}>
                <div style={{ marginBottom: 12 }}><Icon name="check" size={32} /></div>
                <strong style={{ display: 'block', fontSize: 16, marginBottom: 4 }}>Ticket Submitted</strong>
                <p style={{ margin: 0, fontSize: 14 }}>Our team has received your request.</p>
              </div>
            ) : (
              <form onSubmit={handleTicketSubmit} className="col gap-16">
                <div className="form-group">
                  <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Category</label>
                  <select 
                    value={ticketCategory} 
                    onChange={e => setTicketCategory(e.target.value)} 
                    className="login-input" 
                    style={{ appearance: 'auto', padding: '10px 14px' }}
                  >
                    <option>Technical Issue</option>
                    <option>Curriculum Question</option>
                    <option>Account Access</option>
                    <option>Other</option>
                  </select>
                </div>
                
                <div className="form-group">
                  <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Subject</label>
                  <input 
                    type="text" 
                    value={ticketSubject} 
                    onChange={e => setTicketSubject(e.target.value)} 
                    className="login-input" 
                    placeholder="Brief description" 
                    required 
                  />
                </div>
                
                <div className="form-group">
                  <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Message</label>
                  <textarea 
                    value={ticketMessage} 
                    onChange={e => setTicketMessage(e.target.value)} 
                    className="login-input" 
                    placeholder="Please describe your issue in detail..." 
                    rows={4} 
                    style={{ resize: 'vertical' }}
                    required 
                  />
                </div>
                
                <button type="submit" className="btn btn-primary" disabled={ticketStatus === 'loading'}>
                  {ticketStatus === 'loading' ? 'Submitting...' : 'Send Message'}
                </button>
              </form>
            )}
          </div>
          
        </div>
        
      </div>
    </div>
  );
}

window.SupportPage = SupportPage;
