// Inject keyframes once
if (!document.getElementById("dd-kf")) {
  const s = document.createElement("style");
  s.id = "dd-kf";
  s.textContent = `
    @keyframes dd-fade-up {
      from { opacity: 0; transform: translateY(28px); }
      to   { opacity: 1; transform: translateY(0);    }
    }
    @keyframes dd-fade-in {
      from { opacity: 0; } to { opacity: 1; }
    }
    @keyframes dd-glow-pulse {
      0%, 100% { opacity: 0.18; }
      50%       { opacity: 0.32; }
    }
    .dd-card {
      transition: transform 200ms ease, box-shadow 200ms ease, border-color 200ms ease;
    }
    .dd-card:hover {
      transform: translateY(-4px);
      box-shadow: 0 16px 48px rgba(0,0,0,0.5), 0 0 0 1px rgba(77,163,120,0.18);
      border-color: rgba(77,163,120,0.25) !important;
    }
    .dd-link-card {
      transition: transform 200ms ease, background 200ms ease, border-color 200ms ease;
    }
    .dd-link-card:hover {
      transform: translateY(-3px);
      background: rgba(255,255,255,0.06) !important;
      border-color: rgba(77,163,120,0.3) !important;
    }
    .dd-back-btn {
      transition: color 150ms, background 150ms;
    }
    .dd-back-btn:hover {
      color: var(--fg-1) !important;
      background: var(--bg-muted) !important;
    }
    .dd-mock-btn {
      transition: box-shadow 200ms, transform 150ms, background 150ms;
    }
    .dd-mock-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 0 32px rgba(77,163,120,0.5), 0 8px 24px rgba(0,0,0,0.3) !important;
    }
    .dd-yt-btn {
      transition: background 150ms, color 150ms;
    }
    .dd-yt-btn:hover {
      background: var(--bg-muted) !important;
      color: var(--fg-1) !important;
    }
  `;
  document.head.appendChild(s);
}

const TYPE_META = {
  dsa:           { label: "DSA",          color: "#63b78e", glow: "rgba(99,183,142,0.15)"  },
  technical:     { label: "Technical",    color: "#63b78e", glow: "rgba(99,183,142,0.15)"  },
  system_design: { label: "Sys Design",   color: "#60a5fa", glow: "rgba(96,165,250,0.15)"  },
  behavioral:    { label: "Behavioral",   color: "#fbbf24", glow: "rgba(251,191,36,0.15)"  },
  mixed:         { label: "Mixed",        color: "#a1a1aa", glow: "rgba(161,161,170,0.10)" },
};

function anim(delay = 0) {
  return { animation: `dd-fade-up 500ms cubic-bezier(.22,.68,0,1.2) ${delay}ms both` };
}

function DayDetail({ day, onBack, onStartMock, darkMode = false }) {
  const pageBg = darkMode
    ? "radial-gradient(circle at 18% 12%, rgba(255,255,255,.06), transparent 22%), linear-gradient(180deg, #1c1d21 0%, #131416 100%)"
    : "radial-gradient(circle at 18% 8%, rgba(255,255,255,.92), transparent 22%), linear-gradient(180deg, #f7f8fa 0%, #eef1f4 100%)";

  if (!day) {
    return (
      <div style={{ minHeight: "100vh", background: pageBg, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ textAlign: "center", color: "#71717a" }}>
          <div style={{ font: "16px var(--font-sans)", marginBottom: 20 }}>No day selected.</div>
          <button onClick={onBack} className="dd-back-btn" style={{
            padding: "8px 18px", borderRadius: 8, border: "1px solid rgba(255,255,255,0.1)",
            background: "transparent", color: "#a1a1aa", font: "500 15px var(--font-sans)", cursor: "pointer",
          }}>← Back</button>
        </div>
      </div>
    );
  }

  const meta         = TYPE_META[day.type] || TYPE_META.mixed;
  const todayStr     = new Date().toISOString().slice(0, 10);
  const isToday      = day.date === todayStr;
  const dateFormatted = day.date
    ? new Date(day.date + "T12:00:00").toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })
    : "";
  const hasResources = (Array.isArray(day.youtube) && day.youtube.length > 0) || (Array.isArray(day.resources) && day.resources.length > 0);

  const text1 = darkMode ? "#f3f4f6" : "#0a0a0b";
  const text2 = darkMode ? "#a1a1aa" : "#52525b";
  const text3 = darkMode ? "#52525b" : "#9ca3af";
  const backBorder = darkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.09)";
  const backBg = darkMode ? "rgba(255,255,255,0.03)" : "rgba(0,0,0,0.03)";
  const backColor = darkMode ? "#71717a" : "#6b7280";
  const cardBorder = darkMode ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.08)";
  const cardBg = darkMode ? "rgba(255,255,255,0.03)" : "rgba(255,255,255,0.72)";
  const sectionLabel = darkMode ? "#52525b" : "#9ca3af";
  const taskText = darkMode ? "#d4d4d8" : "#374151";
  const resourceTitle = darkMode ? "#e4e4e7" : "#111827";

  return (
    <div style={{ minHeight: "100vh", background: pageBg, color: text1, overflow: "hidden" }}>

      {/* ── Ambient glow ─────────────────────────────────────── */}
      <div style={{
        position: "fixed", top: -200, left: "50%", transform: "translateX(-50%)",
        width: 900, height: 500, borderRadius: "50%",
        background: `radial-gradient(ellipse, ${meta.glow} 0%, transparent 70%)`,
        pointerEvents: "none", zIndex: 0,
        animation: "dd-glow-pulse 4s ease-in-out infinite",
      }} />

      {/* ── Content ──────────────────────────────────────────── */}
      <div style={{ position: "relative", zIndex: 1, maxWidth: 960, margin: "0 auto", padding: "28px 40px 80px" }}>

        {/* Back */}
        <button onClick={onBack} className="dd-back-btn" style={{
          display: "inline-flex", alignItems: "center", gap: 7,
          padding: "7px 14px", borderRadius: 8,
          border: `1px solid ${backBorder}`,
          background: backBg,
          font: "500 15px var(--font-sans)", color: backColor,
          cursor: "pointer", marginBottom: 48,
          ...anim(0),
        }}>
          <Icon name="arrow-left" size={13} color="#71717a" />
          Back to plan
        </button>

        {/* ── Hero ──────────────────────────────────────────────── */}
        <div style={{ position: "relative", marginBottom: 64 }}>
          {/* Oversized day watermark */}
          <div style={{
            position: "absolute", top: -40, right: -20,
            font: "900 200px var(--font-sans)", letterSpacing: "-0.06em",
            color: "rgba(255,255,255,0.025)", lineHeight: 1,
            userSelect: "none", pointerEvents: "none",
            animation: "dd-fade-in 800ms 100ms both",
          }}>{String(day.day).padStart(2, "0")}</div>

          {/* Type badge */}
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "5px 12px", borderRadius: 999, marginBottom: 20,
            border: `1px solid ${meta.color}30`,
            background: `${meta.color}12`,
            ...anim(80),
          }}>
            <div style={{ width: 6, height: 6, borderRadius: 999, background: meta.color }} />
            <span style={{ font: "600 13px var(--font-sans)", letterSpacing: "0.08em", textTransform: "uppercase", color: meta.color }}>
              {meta.label}
            </span>
            {isToday && (
              <>
                <div style={{ width: 1, height: 10, background: "rgba(255,255,255,0.15)" }} />
                <span style={{ font: "600 13px var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "#63b78e" }}>Today</span>
              </>
            )}
            {day.mock && (
              <>
                <div style={{ width: 1, height: 10, background: "rgba(255,255,255,0.15)" }} />
                <span style={{ font: "600 13px var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "#60a5fa" }}>Mock day</span>
              </>
            )}
          </div>

          {/* Title */}
          <h1 style={{
            font: "800 64px/1.05 var(--font-sans)", letterSpacing: "-0.035em",
            margin: "0 0 16px",
            background: `linear-gradient(135deg, #fff 30%, ${meta.color} 100%)`,
            WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent",
            backgroundClip: "text",
            maxWidth: 640,
            ...anim(120),
          }}>{day.focus}</h1>

          {/* Date + actions */}
          <div style={{ display: "flex", alignItems: "center", gap: 16, ...anim(180) }}>
            <span style={{ font: "16px var(--font-sans)", color: text2 }}>{dateFormatted}</span>
            <button onClick={onStartMock} className="dd-mock-btn" style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              height: 40, padding: "0 20px", borderRadius: 10, border: "none",
              background: "linear-gradient(135deg, #4da378, #35825a)",
              color: "#fff", font: "600 16px var(--font-sans)", cursor: "pointer",
              boxShadow: "0 0 20px rgba(77,163,120,0.35), 0 4px 16px rgba(0,0,0,0.4)",
            }}>
              <Icon name="video" size={14} color="#fff" />
              Start mock
            </button>
          </div>
        </div>

        {/* ── Two-column grid ─────────────────────────────────── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>

          {/* ── Tasks column ─────────────────────────────────── */}
          {day.tasks?.length > 0 && (
            <div style={anim(240)}>
              <div style={{
                font: "600 12px var(--font-sans)", letterSpacing: "0.12em",
                textTransform: "uppercase", color: sectionLabel, marginBottom: 14,
              }}>Tasks</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {day.tasks.map((task, i) => (
                  <TaskItem key={i} task={task} delay={260 + i * 50} color={meta.color} taskText={taskText} doneText={text3} />
                ))}
              </div>
            </div>
          )}

          {/* ── Resources column ────────────────────────────── */}
          {hasResources && (
            <div>
              {/* YouTube */}
              {day.youtube?.length > 0 && (
                <div style={{ marginBottom: 28, ...anim(300) }}>
                  <div style={{
                    font: "600 12px var(--font-sans)", letterSpacing: "0.12em",
                    textTransform: "uppercase", color: "#3f3f46", marginBottom: 14,
                  }}>YouTube</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    {day.youtube.map((yt, i) => (
                      <YTCard key={i} yt={yt} delay={320 + i * 60} />
                    ))}
                  </div>
                </div>
              )}

              {/* Reference links */}
              {day.resources?.length > 0 && (
                <div style={anim(360)}>
                  <div style={{
                    font: "600 12px var(--font-sans)", letterSpacing: "0.12em",
                    textTransform: "uppercase", color: "#3f3f46", marginBottom: 14,
                  }}>References</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {day.resources.map((r, i) => (
                      <ResourceCard key={i} r={r} delay={380 + i * 50} titleColor={resourceTitle} descColor={text2} />
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* No resources */}
          {!hasResources && (
            <div style={{ ...anim(280), padding: "32px 28px", borderRadius: 16, border: "1px solid rgba(255,255,255,0.06)", background: "rgba(255,255,255,0.02)", textAlign: "center" }}>
              <Icon name="refresh-cw" size={24} color="#3f3f46" />
              <div style={{ font: "500 15px var(--font-sans)", color: text2, marginTop: 12 }}>No resources attached</div>
              <div style={{ font: "14px var(--font-sans)", color: text3, marginTop: 4 }}>Regenerate your study plan to get recommendations.</div>
            </div>
          )}
        </div>

        {/* ── Mock CTA banner ─────────────────────────────────── */}
        {day.mock && (
          <div style={{
            marginTop: 48,
            padding: "28px 32px",
            borderRadius: 18,
            border: "1px solid rgba(77,163,120,0.2)",
            background: "linear-gradient(135deg, rgba(77,163,120,0.08) 0%, rgba(53,130,90,0.04) 100%)",
            display: "flex", alignItems: "center", gap: 20,
            boxShadow: "0 0 60px rgba(77,163,120,0.06)",
            ...anim(440),
          }}>
            <div style={{
              width: 52, height: 52, borderRadius: 14, flexShrink: 0,
              background: "linear-gradient(135deg, #4da378, #35825a)",
              display: "flex", alignItems: "center", justifyContent: "center",
              boxShadow: "0 0 24px rgba(77,163,120,0.4)",
            }}>
              <Icon name="video" size={22} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: "700 18px var(--font-sans)", color: "#63b78e", marginBottom: 4 }}>Mock interview day</div>
              <div style={{ font: "15px var(--font-sans)", color: text2, lineHeight: 1.5 }}>
                You've prepped — now put it to the test with a full live session with Ari.
              </div>
            </div>
            <button onClick={onStartMock} className="dd-mock-btn" style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              height: 44, padding: "0 24px", borderRadius: 10, border: "none",
              background: "linear-gradient(135deg, #4da378, #35825a)",
              color: "#fff", font: "600 16px var(--font-sans)", cursor: "pointer",
              boxShadow: "0 0 24px rgba(77,163,120,0.4), 0 4px 16px rgba(0,0,0,0.4)",
              flexShrink: 0,
            }}>
              <Icon name="video" size={15} color="#fff" />
              Start session
            </button>
          </div>
        )}

      </div>
    </div>
  );
}

function TaskItem({ task, delay, color, taskText = "#d4d4d8", doneText = "#52525b" }) {
  const [done, setDone] = React.useState(false);
  return (
    <div
      onClick={() => setDone(d => !d)}
      className="dd-card"
      style={{
        display: "flex", alignItems: "flex-start", gap: 14,
        padding: "14px 16px", borderRadius: 12, cursor: "pointer",
        border: `1px solid ${done ? color + "30" : "var(--border-1)"}`,
        background: done ? `${color}08` : "var(--bg-subtle)",
        animation: `dd-fade-up 500ms cubic-bezier(.22,.68,0,1.2) ${delay}ms both`,
      }}
    >
      <div style={{
        width: 18, height: 18, borderRadius: 5, flexShrink: 0, marginTop: 1,
        border: `1.5px solid ${done ? color : "var(--border-2)"}`,
        background: done ? color : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center",
        transition: "all 200ms ease",
      }}>
        {done && <Icon name="check" size={10} color="#fff" />}
      </div>
      <span style={{
        font: "15px/1.55 var(--font-sans)",
        color: done ? doneText : taskText,
        textDecoration: done ? "line-through" : "none",
        transition: "color 200ms, text-decoration 200ms",
      }}>{task}</span>
    </div>
  );
}

function YTCard({ yt, delay }) {
  // New format: { title, url, description }
  // Old format: { query, recent_url, popular_url }
  const isDirectLink = !!yt.url;
  const title = yt.title || yt.query || "YouTube video";
  const desc  = yt.description || "";

  return (
    <a
      href={isDirectLink ? yt.url : (yt.recent_url || "#")}
      target="_blank" rel="noopener noreferrer"
      style={{ textDecoration: "none" }}
    >
      <div style={{
        borderRadius: 14, overflow: "hidden",
        border: "1px solid rgba(255,255,255,0.07)",
        background: "rgba(255,255,255,0.03)",
        animation: `dd-fade-up 500ms cubic-bezier(.22,.68,0,1.2) ${delay}ms both`,
        transition: "border-color 150ms, background 150ms",
        cursor: "pointer",
      }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = "rgba(255,80,80,0.3)"; e.currentTarget.style.background = "rgba(255,0,0,0.06)"; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = "rgba(255,255,255,0.07)"; e.currentTarget.style.background = "rgba(255,255,255,0.03)"; }}
      >
        <div style={{
          padding: "14px 16px",
          background: "linear-gradient(135deg, rgba(255,0,0,0.18) 0%, rgba(180,0,0,0.12) 100%)",
          borderBottom: "1px solid rgba(255,255,255,0.06)",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: 7, flexShrink: 0,
            background: "rgba(255,0,0,0.3)", border: "1px solid rgba(255,80,80,0.3)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon name="play" size={12} color="#ff6b6b" />
          </div>
          <span style={{ font: "600 14px var(--font-sans)", color: "#fca5a5", lineHeight: 1.3 }}>{title}</span>
          <Icon name="external-link" size={12} color="#71717a" style={{ marginLeft: "auto", flexShrink: 0 }} />
        </div>
        {desc && (
          <div style={{ padding: "10px 16px", font: "13px/1.5 var(--font-sans)", color: "#71717a" }}>
            {desc}
          </div>
        )}
        {/* Old format: show both recent + popular links */}
        {!isDirectLink && (
          <div style={{ padding: "10px 14px", display: "flex", gap: 8 }}>
            <a href={yt.recent_url} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="dd-yt-btn" style={{
              flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
              padding: "8px 0", borderRadius: 8, textDecoration: "none",
              background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.08)",
              font: "500 13px var(--font-sans)", color: "#a1a1aa",
            }}>
              <Icon name="clock" size={12} color="#71717a" /> Recent
            </a>
            <a href={yt.popular_url} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="dd-yt-btn" style={{
              flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
              padding: "8px 0", borderRadius: 8, textDecoration: "none",
              background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.08)",
              font: "500 13px var(--font-sans)", color: "#a1a1aa",
            }}>
              <Icon name="trending-up" size={12} color="#71717a" /> Popular
            </a>
          </div>
        )}
      </div>
    </a>
  );
}

function ResourceCard({ r, delay, titleColor = "#e4e4e7", descColor = "#a1a1aa" }) {
  if (r == null || typeof r !== "object") {
    return (
      <div style={{
        padding: "12px 16px", borderRadius: 12,
        border: "1px solid rgba(255,255,255,0.07)",
        background: "rgba(255,255,255,0.03)",
        font: "15px var(--font-sans)", color: "#71717a",
        animation: `dd-fade-up 500ms cubic-bezier(.22,.68,0,1.2) ${delay}ms both`,
      }}>{r}</div>
    );
  }
  return (
    <a href={/^https?:\/\//i.test(r.url || "") ? r.url : "#"} target="_blank" rel="noopener noreferrer" className="dd-link-card" style={{
      textDecoration: "none", borderRadius: 12,
      border: "1px solid rgba(255,255,255,0.07)",
      background: "rgba(255,255,255,0.03)",
      padding: "14px 16px",
      display: "flex", alignItems: "flex-start", gap: 12,
      animation: `dd-fade-up 500ms cubic-bezier(.22,.68,0,1.2) ${delay}ms both`,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 9, flexShrink: 0,
        background: "rgba(77,163,120,0.1)", border: "1px solid rgba(77,163,120,0.15)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name="book-open" size={16} color="#63b78e" />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: "600 15px var(--font-sans)", color: titleColor, marginBottom: 3 }}>{r.title}</div>
        {r.description && (
          <div style={{ font: "14px/1.5 var(--font-sans)", color: descColor, marginBottom: 5 }}>{r.description}</div>
        )}
        <div style={{
          font: "13px var(--font-mono)", color: "#3f3f46",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        }}>{r.url}</div>
      </div>
      <Icon name="external-link" size={13} color="#3f3f46" style={{ flexShrink: 0, marginTop: 3 }} />
    </a>
  );
}

window.DayDetail = DayDetail;
