// ============ Tareas, Foro, Certificados, Progreso, Calendario, Sala ============

function SubmitPanel({ onSubmit, submitted }) {
  const [files, setFiles] = useState([]);
  const [note, setNote] = useState("");
  const fileInputRef = useRef(null);

  if (submitted) {
    return (
      <div className="submit-done">
        <div className="sd-ico"><Icon name="checkc" size={26} /></div>
        <div><strong>Entrega enviada</strong><span>Recibirás retroalimentación de tu instructor pronto.</span></div>
      </div>
    );
  }

  const handleFileChange = (e) => {
    const selected = Array.from(e.target.files).map(f => ({
      n: f.name,
      s: f.size > 1024 * 1024 
        ? `${(f.size / (1024 * 1024)).toFixed(1)} MB` 
        : `${Math.ceil(f.size / 1024)} KB`
    }));
    setFiles(selected);
  };

  return (
    <div className="submit-panel">
      <input type="file" ref={fileInputRef} style={{ display: "none" }} onChange={handleFileChange} />
      <div className="dropzone" onClick={() => fileInputRef.current && fileInputRef.current.click()}>
        <Icon name="download" size={26} />
        <strong>Selecciona un archivo para tu entrega</strong>
        <span>Haz clic para seleccionar · PDF, DOCX, XLSX (máx 20 MB)</span>
      </div>
      {files.map((f, i) => (
        <div key={i} className="file-chip"><Icon name="file" size={18} /><span>{f.n}</span><em>{f.s}</em>
          <button onClick={() => setFiles(files.filter((_, k) => k !== i))}><Icon name="x" size={16} /></button></div>
      ))}
      <textarea className="note-field" placeholder="Agrega una nota para tu instructor (opcional)…" value={note} onChange={(e) => setNote(e.target.value)} />
      <Btn variant="primary" icon="send" disabled={!files.length} onClick={() => onSubmit(note, files[0] ? files[0].n : "entrega.pdf")}>Enviar entrega</Btn>
    </div>
  );
}

function TareaInline({ title, course, go, courseId }) {
  const [submitted, setSubmitted] = useState(false);
  const assignment = (window.DATA && DATA.assignments) 
    ? DATA.assignments.find(a => a.course_id === courseId && (a.title.toLowerCase().includes(title.toLowerCase()) || title.toLowerCase().includes(a.title.toLowerCase())))
    : null;

  return (
    <div className="tarea-inline">
      <div className="ti-head"><Badge tone="orange">Tarea</Badge><h2>{title}</h2><span className="ti-course">{course}</span></div>
      <div className="prose"><p>Aplica lo aprendido en esta semana. Sube tu entrega en el panel inferior; tu instructor la revisará y te dará retroalimentación.</p></div>
      <SubmitPanel 
        submitted={submitted || (assignment && assignment.status === "submitted")} 
        onSubmit={(note, filename) => {
          setSubmitted(true);
          if (assignment) {
            API.submitAssignment(assignment.id, note, filename)
              .then((saved) => { window.DATA.assignments = DATA.assignments.map((a) => a.id === saved.id ? saved : a); })
              .catch((err) => console.warn("No se pudo guardar la entrega", err));
          }
        }} 
      />
    </div>
  );
}

function TasksScreen({ go, openId }) {
  const [open, setOpen] = useState(openId || null);
  const [submittedMap, setSubmittedMap] = useState({});
  const groups = [
    ["Pendientes", DATA.assignments.filter((a) => a.status === "pending" && !submittedMap[a.id])],
    ["Enviadas", DATA.assignments.filter((a) => a.status === "submitted" || submittedMap[a.id])],
    ["Calificadas", DATA.assignments.filter((a) => a.status === "graded")],
  ];
  const active = DATA.assignments.find((a) => a.id === open);

  return (
    <div className="screen tasks">
      {groups.map(([label, items]) => items.length > 0 && (
        <div key={label} className="task-group">
          <h3 className="tg-title">{label} <span>{items.length}</span></h3>
          <div className="task-cards">
            {items.map((a) => {
              const isSub = a.status === "submitted" || submittedMap[a.id];
              const isGraded = a.status === "graded";
              const dl = dueLabel(a.due);
              return (
                <div key={a.id} className="task-card" onClick={() => setOpen(a.id)}>
                  <div className={"tc-flag " + (isGraded ? "graded" : isSub ? "sub" : dl.tone)} />
                  <div className="tc-main">
                    <div className="tc-top">
                      <h4>{a.title}</h4>
                      {isGraded ? <Badge tone="green">{a.grade}</Badge> : isSub ? <Badge tone="navy">Enviada</Badge> : <Badge tone={dl.tone}>{dl.txt}</Badge>}
                    </div>
                    <span className="tc-course"><Icon name="book" size={14} /> {a.course}</span>
                    <p>{a.desc}</p>
                  </div>
                  <Icon name="chevR" size={20} className="tc-arrow" />
                </div>
              );
            })}
          </div>
        </div>
      ))}

      {active && (
        <div className="modal-overlay" onClick={() => setOpen(null)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-head">
              <div><Badge tone="orange">Tarea</Badge><h2>{active.title}</h2><span>{active.course}</span></div>
              <button className="icon-btn" onClick={() => setOpen(null)}><Icon name="x" size={20} /></button>
            </div>
            <div className="modal-body">
              <div className="prose"><p>{active.desc}</p></div>
              {active.status === "graded" ? (
                <div className="graded-box">
                  <div className="gb-score"><span>Calificación</span><strong>{active.grade}</strong></div>
                  <div className="gb-fb"><strong>Retroalimentación del instructor</strong><p>{active.feedback}</p></div>
                </div>
              ) : (
                <SubmitPanel submitted={active.status === "submitted" || submittedMap[active.id]}
                  onSubmit={(note, filename) => {
                    setSubmittedMap((m) => ({ ...m, [active.id]: true }));
                    API.submitAssignment(active.id, note, filename)
                      .then((saved) => { window.DATA.assignments = DATA.assignments.map((a) => a.id === saved.id ? saved : a); })
                      .catch((err) => console.warn("No se pudo guardar la entrega", err));
                  }} />
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Foro ----------
function Forum({ go }) {
  const [posts, setPosts] = useState(DATA.forum);
  const [draft, setDraft] = useState(false);
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const like = (id) => {
    setPosts((p) => p.map((x) => x.id === id ? { ...x, liked: !x.liked, likes: x.likes + (x.liked ? -1 : 1) } : x));
    API.likePost(id)
      .then((saved) => setPosts((p) => p.map((x) => x.id === id ? saved : x)))
      .catch((err) => console.warn("No se pudo guardar el like", err));
  };
  const publish = () => {
    if (!title.trim()) return;
    const user = DATA.user || { name: "Alumno", company: "DataVoices & SynapTech", avatar: "AL" };
    const getInitials = (name) => name.split(" ").slice(0, 2).map(n => n[0]).join("").toUpperCase() || "AL";
    const userInit = user.avatar || getInitials(user.name);
    
    const draftPost = { 
      id: Date.now(), 
      author: user.name, 
      company: user.company || "DataVoices & SynapTech", 
      initials: userInit, 
      time: "ahora", 
      course: "General", 
      title, 
      body, 
      replies: 0, 
      likes: 0, 
      liked: false 
    };
    setPosts((p) => [draftPost, ...p]);
    API.publishPost({ title, body, course: "General" })
      .then((saved) => setPosts((p) => [saved, ...p.filter((x) => x.id !== draftPost.id)]))
      .catch((err) => console.warn("No se pudo publicar", err));
    setTitle(""); setBody(""); setDraft(false);
  };
  const sorted = [...posts].sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0));
  return (
    <div className="screen forum">
      <div className="forum-head">
        <p>Comparte dudas, recursos y aprendizajes con tu equipo y los instructores de DataVoices &amp; SynapTech.</p>
        <Btn variant="primary" icon="send" onClick={() => setDraft((d) => !d)}>Nueva publicación</Btn>
      </div>
      {draft && (
        <div className="forum-draft">
          <input className="fd-title" placeholder="Título de tu publicación" value={title} onChange={(e) => setTitle(e.target.value)} />
          <textarea className="fd-body" placeholder="Escribe tu mensaje…" value={body} onChange={(e) => setBody(e.target.value)} />
          <div className="fd-actions"><Btn variant="ghost" size="sm" onClick={() => setDraft(false)}>Cancelar</Btn><Btn variant="primary" size="sm" icon="send" onClick={publish}>Publicar</Btn></div>
        </div>
      )}
      <div className="forum-list">
        {sorted.map((p) => (
          <div key={p.id} className="forum-post">
            <Avatar text={p.initials} size={44} bg={p.company.includes("SynapTech") ? "var(--synap-teal)" : p.company.includes("DataVoices") ? "var(--orange)" : "var(--navy)"} />
            <div className="fp-body">
              <div className="fp-top">
                {p.pinned && <span className="fp-pin"><Icon name="pin" size={14} /> Fijado</span>}
                <strong>{p.author}</strong>
                <span className="fp-meta">{p.company} · {p.time}</span>
              </div>
              <span className="fp-course"><Icon name="book" size={13} /> {p.course}</span>
              <h4>{p.title}</h4>
              <p>{p.body}</p>
              <div className="fp-actions">
                <button className={"fp-act" + (p.liked ? " active" : "")} onClick={() => like(p.id)}><Icon name="heart" size={17} /> {p.likes}</button>
                <button className="fp-act"><Icon name="chat" size={17} /> {p.replies} respuestas</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- Certificados ----------
function Certificates({ go }) {
  const certs = DATA.certificates;
  const inProgress = DATA.courses.filter((c) => c.progress > 0 && c.progress < 100);
  return (
    <div className="screen certs">
      {certs.map((ce) => (
        <div key={ce.id} className="cert">
          <div className="cert-paper">
            <div className="cert-top"><Logo /><span className="cert-seal"><Icon name="award" size={26} /></span></div>
            <span className="cert-eyebrow">CERTIFICADO DE FINALIZACIÓN</span>
            <p className="cert-grants">Se otorga el presente certificado a</p>
            <h2 className="cert-name">{DATA.user.name}</h2>
            <p className="cert-for">por completar satisfactoriamente el curso</p>
            <h3 className="cert-course">{ce.course}</h3>
            <div className="cert-foot">
              <div><strong>{ce.date}</strong><span>Fecha de emisión</span></div>
              <div><strong>{ce.hours}</strong><span>Duración</span></div>
              <div><strong>{ce.code}</strong><span>Folio de verificación</span></div>
            </div>
          </div>
          <div className="cert-actions">
            <Btn variant="primary" icon="download">Descargar PDF</Btn>
            <Btn variant="ghost" icon="send">Compartir en LinkedIn</Btn>
          </div>
        </div>
      ))}
      {inProgress.length > 0 && (
        <div className="cert-pending">
          <h3>En camino a tu próximo certificado</h3>
          <div className="cp-list">
            {inProgress.map((c) => (
              <div key={c.id} className="cp-item" onClick={() => go("curso", { courseId: c.id })}>
                <div className="cp-ring"><Ring value={c.progress} size={48} sw={5} /></div>
                <div className="cp-info"><strong>{c.title}</strong><span>Completa el curso para obtener tu certificado</span></div>
                <Icon name="chevR" size={20} />
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Progreso ----------
function Progress({ go }) {
  const total = DATA.courses.length ? Math.round(DATA.courses.reduce((s, c) => s + c.progress, 0) / DATA.courses.length) : 0;
  const completed = DATA.courses.filter((c) => c.progress === 100).length;
  const lessonsDone = DATA.courses.reduce((s, c) => s + c.modules.reduce((a, m) => a + m.lessons.filter((l) => l.done).length, 0), 0);
  const estimatedHours = DATA.courses.reduce((totalHours, c) => {
    const hrVal = parseFloat(c.hours) || 0;
    return totalHours + (hrVal * (c.progress / 100));
  }, 0).toFixed(1);
  const stats = [["trending", total + "%", "Avance global"], ["award", completed, "Cursos completados"], ["playc", lessonsDone, "Lecciones vistas"], ["clock", estimatedHours + " h", "Tiempo de estudio"]];
  return (
    <div className="screen progress">
      <div className="prog-stats">
        {stats.map(([ic, n, l], i) => (
          <div key={i} className="prog-stat"><div className="ps-ico"><Icon name={ic} size={22} /></div><strong>{n}</strong><span>{l}</span></div>
        ))}
      </div>
      <div className="panel">
        <div className="panel-head"><h3>Avance por curso</h3></div>
        <div className="prog-courses">
          {DATA.courses.map((c) => {
            const dl = c.modules.reduce((s, m) => s + m.lessons.length, 0);
            const dd = c.modules.reduce((s, m) => s + m.lessons.filter((l) => l.done).length, 0);
            return (
              <div key={c.id} className="prog-course" onClick={() => go("curso", { courseId: c.id })}>
                <div className="pc-dot" style={{ background: c.progress === 100 ? "var(--green)" : c.progress > 0 ? "var(--orange)" : "var(--line)" }} />
                <div className="pc-info"><strong>{c.title}</strong><span>{dd}/{dl} lecciones · {c.hours}</span></div>
                <div className="pc-bar"><ProgressBar value={c.progress} color={c.progress === 100 ? "var(--green)" : "var(--orange)"} /></div>
                <strong className="pc-pct">{c.progress}%</strong>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- Calendario ----------
function Calendar({ go }) {
  const upcoming = [...DATA.sessions].sort((a, b) => parseD(a.date) - parseD(b.date));
  const baseDate = upcoming.length > 0 ? parseD(upcoming[0].date) : new Date();
  const year = baseDate.getFullYear();
  const month = baseDate.getMonth();
  const first = new Date(year, month, 1).getDay();
  const days = new Date(year, month + 1, 0).getDate();
  const byDay = {};
  DATA.sessions.forEach((s) => { const d = parseD(s.date); if (d.getMonth() === month && d.getFullYear() === year) (byDay[d.getDate()] = byDay[d.getDate()] || []).push(s); });
  const cells = [];
  for (let i = 0; i < first; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);

  return (
    <div className="screen calendar-screen">
      <div className="cal-layout">
        <div className="cal-grid-wrap panel">
          <div className="cal-month"><h3>{MES_L[month].charAt(0).toUpperCase() + MES_L[month].slice(1)} {year}</h3></div>
          <div className="cal-dow">{["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"].map((d) => <span key={d}>{d}</span>)}</div>
          <div className="cal-grid">
            {cells.map((d, i) => (
              <div key={i} className={"cal-cell" + (d === TODAY.getDate() ? " today" : "") + (d ? "" : " empty")}>
                {d && <span className="cc-num">{d}</span>}
                {d && byDay[d] && byDay[d].map((s) => (
                  <button key={s.id} className="cc-event" onClick={() => go("sala", { sessionId: s.id })}>{s.time.split(" ")[0]} {s.title.split(":")[0]}</button>
                ))}
              </div>
            ))}
          </div>
        </div>
        <div className="cal-side panel">
          <div className="panel-head"><h3>Próximas sesiones</h3></div>
          <div className="cal-upcoming">
            {upcoming.map((s) => {
              const d = parseD(s.date);
              return (
                <div key={s.id} className="cu-item">
                  <div className="cu-date"><b>{d.getDate()}</b><span>{MES[d.getMonth()]}</span></div>
                  <div className="cu-body"><strong>{s.title}</strong><span>{s.time} · {s.host}</span><em>{s.course}</em></div>
                  {s.joinable ? <Btn variant="primary" size="sm" icon="video" onClick={() => go("sala", { sessionId: s.id })}>Unirme</Btn> : <Btn variant="ghost" size="sm" icon="bell">Recordar</Btn>}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Sala de sesión en vivo ----------
function LiveRoom({ sessionId, go }) {
  const s = DATA.sessions.find((x) => x.id === sessionId) || DATA.sessions[0];
  return (
    <div className="screen live-room">
      <button className="back-link" onClick={() => go("inicio")}><Icon name="arrowL" size={18} /> Volver al inicio</button>
      <div className="live-stage">
        <svg className="player-ph" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 160 90">
          <rect width="160" height="90" fill="#0e0e2c" />
        </svg>
        <div className="live-badge"><span className="live-dot" /> EN VIVO</div>
        <div className="live-info"><h3>{s.title}</h3><span>{s.host} · {s.course}</span></div>
        <div className="live-controls">
          <button className="lc-btn"><Icon name="video" size={20} /></button>
          <button className="lc-btn"><Icon name="chat" size={20} /></button>
          <button className="lc-btn end"><Icon name="x" size={20} /></button>
        </div>
      </div>
    </div>
  );
}

function SupportModal({ onClose }) {
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [done, setDone] = useState(false);
  const [loading, setLoading] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (!subject.trim() || !message.trim()) return;
    setLoading(true);
    API.submitTicket({ subject, message })
      .then(() => {
        setDone(true);
      })
      .catch((err) => {
        console.warn("No se pudo enviar el reclamo", err);
      })
      .finally(() => setLoading(false));
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h2>Soporte DataVoices &amp; SynapTech</h2>
            <span>Carga tu reclamo o duda y nos comunicaremos contigo.</span>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={20} /></button>
        </div>
        <div className="modal-body">
          {done ? (
            <div className="success-state">
              <div className="ss-ico"><Icon name="checkc" size={30} /></div>
              <h3>Reclamo enviado correctamente</h3>
              <p>El equipo de soporte revisará tu caso y te contactará por email.</p>
              <Btn variant="primary" onClick={onClose}>Cerrar</Btn>
            </div>
          ) : (
            <form onSubmit={submit}>
              <div className="form-grid one" style={{ marginBottom: "16px" }}>
                <label className="field">
                  <span className="field-label">Asunto / Tema</span>
                  <input className="inp" value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Ej: No puedo abrir la lección 3" required />
                </label>
                <label className="field">
                  <span className="field-label">Detalle del reclamo</span>
                  <textarea className="inp" style={{ minHeight: "120px" }} value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Escribe aquí tu reclamo..." required />
                </label>
              </div>
              <div className="modal-actions">
                <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
                <Btn variant="primary" icon="send" disabled={loading}>{loading ? "Enviando..." : "Enviar reclamo"}</Btn>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TareaInline, SubmitPanel, TasksScreen, Forum, Certificates, Progress, Calendar, LiveRoom, SupportModal });
