// Parent Dashboard — modern, simple, informative. Echoes student palette but quieter.

const ParentHome = ({ dark = false, go, session }) => {
  const sid = session?.studentId;
  const { data: dash } = useApi(sid ? `/parent/dashboard/${sid}` : "/parent/dashboard/0", {});
  const { data: convos } = useApi("/conversations");
  const [activeConv, setActiveConv] = React.useState(null);
  const [messages, setMessages] = React.useState([]);
  const [reply, setReply] = React.useState("");

  const student      = dash.student      || {};
  const attendance   = dash.attendance   ?? 0;
  const homework     = dash.homework     || { submitted: 0, total: 0 };
  const badges       = dash.badges       || 0;
  const nextClass    = dash.nextClass    || null;
  const lastPayment  = dash.lastPayment  || null;
  const subscription = dash.subscription || null;
  const level        = Math.floor((student.xp || 0) / 500) + 1;
  const childName    = student.name || "—";
  const childAge     = student.age  || "";
  const teacher      = student.teacher || "—";
  const batch        = student.batch || "—";
  const course       = student.course_name ? `${student.course_name} · ${student.course_level}` : "—";
  const parentPhone  = student.parent_phone || null;

  const WELCOME_CONV = { id: "welcome", name: "EpiqMinds Team", avatar: "CL", color: "var(--coral)", last_msg: "Welcome to EpiqMinds!", unread: 1 };
  const displayConvos = convos.length > 0 ? convos : [WELCOME_CONV];

  React.useEffect(() => {
    if (!activeConv) return;
    if (activeConv === "welcome") {
      setMessages([{ id: 1, fromMe: false, text: `Hi ${session?.name || "there"}! Welcome to EpiqMinds. We'll keep you updated on ${childName}'s progress, upcoming classes, homework, and more right here. Feel free to reach out anytime!` }]);
      return;
    }
    apiFetch(`/conversations/${activeConv}/messages`).then(r => r.json()).then(setMessages).catch(() => {});
  }, [activeConv]);

  const sendReply = async () => {
    if (!reply.trim() || !activeConv || activeConv === "welcome") return;
    await apiFetch(`/conversations/${activeConv}/messages`, { method: "POST", body: JSON.stringify({ from_me: true, text: reply }) });
    setMessages(m => [...m, { id: Date.now(), fromMe: true, text: reply }]);
    setReply("");
  };

  const notifications = [
    badges > 0 && { t: `${childName} earned a certificate`, sub: `${badges} total earned`, time: "Recent", color: "var(--coral)", ic: I.trophy },
    homework.total > 0 && { t: "Homework progress", sub: `${homework.submitted}/${homework.total} submitted`, time: "This term", color: "var(--gold)", ic: I.book },
    nextClass && { t: "Upcoming class", sub: nextClass.topic, time: nextClass.day, color: "var(--moss)", ic: I.calendar },
    lastPayment && { t: "Payment received", sub: `${lastPayment.period} · ${lastPayment.amount}`, time: "Paid", color: "var(--sky)", ic: I.wallet },
  ].filter(Boolean).slice(0, 4);

  return (
    <Themed className={dark ? "theme-dark" : ""} style={{ width: "100%", height: "100%", background: "var(--paper)" }}>
      {/* Top bar */}
      <div style={{
        display: "flex", alignItems: "center", gap: 12, padding: "14px 26px",
        background: "var(--paper-card)", borderBottom: "var(--border-thin)",
      }}>
        <div className="display" style={{ fontSize: 20 }}>
          <span style={{ color: "var(--coral)" }}>Epiq</span>Minds
          <span style={{ color: "var(--ink-mute)", fontSize: 11, marginLeft: 6, fontWeight: 500 }}>family</span>
        </div>
        <div style={{ flex: 1 }}/>
        <button className="btn btn-ghost" onClick={() => go && go("/app/parent/shop")} style={{ padding: "6px 12px", fontSize: 12 }}>{I.rocket({ size: 14 })} Shop</button>
        <div className="chip"><Avatar name={(session?.name || "P")[0]} color="var(--sky)" size={22}/> {session?.name || "Parent"}</div>
      </div>

      <div style={{ padding: 26, display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 22 }}>
        {/* Left column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {/* Child hero */}
          <div className="card" style={{ padding: 22, display: "flex", gap: 18 }}>
            <div style={{ position: "relative" }}>
              <Avatar name={childName[0] || "?"} color="var(--coral)" size={72}/>
              <span style={{
                position: "absolute", bottom: -4, right: -4,
                background: "var(--gold)", border: "1.5px solid var(--rule-bold)",
                borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 800,
              }}>L{level}</span>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="display" style={{ fontSize: 26 }}>{childName}{childAge ? `, ${childAge}` : ""}</div>
              <div style={{ fontSize: 13, color: "var(--ink-mute)", marginTop: 2 }}>
                {course} · {batch} · {teacher}
              </div>
              <div style={{ display: "flex", gap: 14, marginTop: 14 }}>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>ATTENDANCE</div>
                  <div className="display" style={{ fontSize: 22 }}>{attendance}<span style={{ fontSize: 14, color: "var(--ink-mute)" }}>%</span></div>
                </div>
                <div className="divider" style={{ width: 1.5, height: 36, alignSelf: "center" }}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>XP</div>
                  <div className="display" style={{ fontSize: 22 }}>{student.xp || 0}</div>
                </div>
                <div className="divider" style={{ width: 1.5, height: 36, alignSelf: "center" }}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>HOMEWORK</div>
                  <div className="display" style={{ fontSize: 22 }}>{homework.submitted}<span style={{ fontSize: 14, color: "var(--ink-mute)" }}>/{homework.total}</span></div>
                </div>
                <div className="divider" style={{ width: 1.5, height: 36, alignSelf: "center" }}/>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>CERTS</div>
                  <div className="display" style={{ fontSize: 22 }}>{badges}</div>
                </div>
              </div>
            </div>
          </div>

          {/* Next class */}
          {nextClass ? (
            <div className="card-flat" style={{ padding: 20, display: "flex", alignItems: "center", gap: 18 }}>
              <div style={{
                width: 56, height: 56, borderRadius: 14, background: "var(--moss)", color: "white",
                border: "var(--border)", boxShadow: "var(--sh-1)",
                display: "grid", placeItems: "center",
              }}>{I.calendar({ size: 24 })}</div>
              <div style={{ flex: 1 }}>
                <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>NEXT CLASS · {nextClass.day.toUpperCase()}</div>
                <div className="display" style={{ fontSize: 20, marginTop: 2 }}>{nextClass.topic}</div>
                <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{nextClass.time} · {nextClass.teacher}</div>
              </div>
              <button className="btn btn-ghost" onClick={() => go && go("/app/parent/schedule")} style={{ padding: "6px 12px", fontSize: 12 }}>Schedule</button>
            </div>
          ) : (
            <div className="card-flat" style={{ padding: 20, display: "flex", alignItems: "center", gap: 18 }}>
              <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--paper-deep)", display: "grid", placeItems: "center" }}>{I.calendar({ size: 24 })}</div>
              <div style={{ flex: 1 }}>
                <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>NEXT CLASS</div>
                <div style={{ fontSize: 14, color: "var(--ink-mute)", marginTop: 4 }}>No upcoming sessions</div>
              </div>
              <button className="btn btn-ghost" onClick={() => go && go("/app/parent/schedule")} style={{ padding: "6px 12px", fontSize: 12 }}>Schedule</button>
            </div>
          )}

          {/* XP progress */}
          <div className="card-flat" style={{ padding: 20 }}>
            <SectionHead eyebrow="THIS TERM" title="XP Progress"/>
            <div style={{ marginTop: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ fontSize: 12, color: "var(--ink-mute)" }}>Level {level}</span>
                <span style={{ fontSize: 12, fontWeight: 700 }}>{student.xp || 0} XP</span>
              </div>
              <div className="progress" style={{ height: 10 }}>
                <i style={{ width: `${Math.min(((student.xp || 0) % 500) / 5, 100)}%`, background: "var(--coral)" }}/>
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 6 }}>{500 - ((student.xp || 0) % 500)} XP to next level</div>
            </div>
          </div>
        </div>

        {/* Right column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>

          {/* Messages panel */}
          <div className="card-flat" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "14px 16px", borderBottom: "var(--border-thin)", display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{ flex: 1 }}>
                <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>MESSAGES</div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>Inbox</div>
              </div>
              {convos.length === 0 && <span className="chip" style={{ background: "var(--coral)", color: "white", fontSize: 10 }}>1 new</span>}
            </div>
            <div style={{ display: "flex", height: 220 }}>
              {/* Conversation list */}
              <div style={{ width: 140, borderRight: "var(--border-thin)", overflowY: "auto", flexShrink: 0 }}>
                {displayConvos.map(c => (
                  <div key={c.id} onClick={() => setActiveConv(c.id)} style={{
                    padding: "10px 12px", cursor: "pointer", borderBottom: "var(--border-thin)",
                    background: activeConv === c.id ? "var(--paper-deep)" : "transparent",
                    borderLeft: activeConv === c.id ? "3px solid var(--coral)" : "3px solid transparent",
                  }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                      <Avatar name={c.avatar || c.name[0]} color={c.color || "var(--coral)"} size={24}/>
                      {c.unread > 0 && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--coral)", flexShrink: 0 }}/>}
                    </div>
                    <div style={{ fontSize: 11, fontWeight: 700, marginTop: 5, lineHeight: 1.3 }}>{c.name}</div>
                    <div style={{ fontSize: 10, color: "var(--ink-mute)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.last_msg}</div>
                  </div>
                ))}
              </div>

              {/* Message thread */}
              <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
                {!activeConv ? (
                  <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, color: "var(--ink-mute)" }}>
                    {I.send({ size: 22 })}
                    <div style={{ fontSize: 12 }}>Select a conversation</div>
                  </div>
                ) : (
                  <>
                    <div style={{ flex: 1, overflowY: "auto", padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8 }}>
                      {messages.map(m => (
                        <div key={m.id} style={{ display: "flex", justifyContent: m.fromMe ? "flex-end" : "flex-start" }}>
                          <div style={{
                            maxWidth: "80%", padding: "7px 11px", borderRadius: m.fromMe ? "12px 12px 2px 12px" : "12px 12px 12px 2px",
                            background: m.fromMe ? "var(--coral)" : "var(--paper-card)",
                            color: m.fromMe ? "white" : "var(--ink)",
                            border: m.fromMe ? "none" : "var(--border-thin)",
                            fontSize: 12, lineHeight: 1.5,
                          }}>{m.text}</div>
                        </div>
                      ))}
                    </div>
                    {activeConv !== "welcome" && (
                      <div style={{ display: "flex", gap: 6, padding: "8px 10px", borderTop: "var(--border-thin)" }}>
                        <input value={reply} onChange={e => setReply(e.target.value)}
                          onKeyDown={e => e.key === "Enter" && sendReply()}
                          placeholder="Type a message…"
                          style={{ flex: 1, border: "var(--border-thin)", borderRadius: 8, padding: "6px 10px", fontSize: 12, fontFamily: "var(--font-ui)", background: "var(--paper-card)", color: "var(--ink)", outline: "none" }}/>
                        <button onClick={sendReply} className="btn btn-primary" style={{ padding: "6px 10px", fontSize: 12 }}>{I.send({ size: 13 })}</button>
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Notifications */}
          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="UPDATES" title="What happened"/>
            {notifications.length === 0 ? (
              <div style={{ fontSize: 13, color: "var(--ink-mute)", padding: "12px 0" }}>No updates yet</div>
            ) : notifications.map((n, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 0",
                borderTop: i ? "var(--border-thin)" : "none",
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 10, background: n.color, color: "white",
                  border: "var(--border-thin)", display: "grid", placeItems: "center", flexShrink: 0,
                }}>{n.ic({ size: 16 })}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{n.t}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{n.sub}</div>
                </div>
                <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>{n.time}</div>
              </div>
            ))}
          </div>

          {/* Subscription details */}
          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="BILLING" title="Subscription"/>
            {subscription ? (
              <>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8 }}>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700 }}>{subscription.plan} Plan</div>
                    <div style={{ fontSize: 12, color: "var(--ink-mute)", marginTop: 2 }}>Due {subscription.due}</div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div className="display" style={{ fontSize: 20 }}>{subscription.amount}</div>
                    <span className="chip" style={{
                      background: subscription.status === "paid" ? "var(--moss)" : subscription.status === "overdue" ? "var(--coral)" : "var(--gold)",
                      color: "white", fontSize: 10, marginTop: 4, display: "inline-block",
                    }}>{subscription.status}</span>
                  </div>
                </div>
                {lastPayment && (
                  <div style={{ marginTop: 10, padding: "8px 12px", background: "var(--paper-deep)", borderRadius: 8, fontSize: 12, color: "var(--ink-mute)" }}>
                    Last payment: {lastPayment.amount} · {lastPayment.period}
                  </div>
                )}
                <button className="btn btn-ghost" style={{ marginTop: 10, width: "100%", justifyContent: "center", padding: "8px 0", fontSize: 12 }}>
                  {I.wallet({ size: 13 })} View all invoices
                </button>
              </>
            ) : (
              <div style={{ fontSize: 13, color: "var(--ink-mute)", padding: "10px 0" }}>No active subscription found</div>
            )}
          </div>

          {/* How we reach you */}
          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="ALERTS" title="How we reach you"/>
            {[
              ["Email", session?.email || "—", true],
              ["WhatsApp", parentPhone || "Not on file", !!parentPhone],
              ["SMS", parentPhone || "Not on file", !!parentPhone],
            ].map(([label, val, on], i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 10, padding: "10px 0",
                borderTop: i ? "var(--border-thin)" : "none",
              }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{label}</div>
                  <div style={{ fontSize: 12, color: on ? "var(--ink-soft)" : "var(--ink-mute)" }}>{val}</div>
                </div>
                <div style={{
                  width: 36, height: 20, borderRadius: 999, padding: 2,
                  background: on ? "var(--moss)" : "var(--paper-deep)",
                  border: "var(--border-thin)",
                }}>
                  <div style={{
                    width: 14, height: 14, borderRadius: "50%", background: "white",
                    marginLeft: on ? 16 : 0, transition: "margin 120ms",
                    border: "1px solid var(--rule)",
                  }}/>
                </div>
              </div>
            ))}
            {!parentPhone && (
              <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 8, padding: "8px 10px", background: "var(--paper-deep)", borderRadius: 8 }}>
                Contact school to register your WhatsApp / SMS number
              </div>
            )}
          </div>
        </div>
      </div>
    </Themed>
  );
};

window.ParentHome = ParentHome;

