/* Admin-lite dashboard */

const SAMPLE_ORDERS = [
  { id: "IJ-2046", name: "Maya Chen", buyer: "jess@gmail.com", type: "Roast", tier: "Quick", status: "needs_review", created: "May 4, 2:14p", price: 29 },
  { id: "IJ-2045", name: "Drew Patel", buyer: "alex@example.com", type: "Hype", tier: "Polished", status: "generating", created: "May 4, 1:02p", price: 69 },
  { id: "IJ-2044", name: "Mom", buyer: "sarah@example.com", type: "Heartfelt", tier: "Polished", status: "delivered", created: "May 3, 7:48p", price: 69 },
  { id: "IJ-2043", name: "Big Hunt", buyer: "league@example.com", type: "Roast", tier: "Quick", status: "delivered", created: "May 3, 4:10p", price: 29 },
  { id: "IJ-2042", name: "Riley + Sam", buyer: "noah@example.com", type: "Romantic", tier: "Polished", status: "intake_submitted", created: "May 3, 11:32a", price: 69 },
  { id: "IJ-2041", name: "Coach G", buyer: "team@example.com", type: "Business", tier: "Polished", status: "paid_intake_pending", created: "May 3, 9:01a", price: 69 },
  { id: "IJ-2040", name: "Aunt Lisa", buyer: "kira@example.com", type: "Birthday/Holiday", tier: "Quick", status: "regen_requested", created: "May 2, 6:55p", price: 29 },
  { id: "IJ-2039", name: "Nina", buyer: "tom@example.com", type: "Roast", tier: "Quick", status: "delivered", created: "May 2, 2:30p", price: 29 },
];

const STATUS_LABELS = {
  paid_intake_pending: { label: "Awaiting intake", color: "#999" },
  intake_submitted: { label: "Intake in", color: "#5C9EAD" },
  generating: { label: "Generating", color: "#FFD23F" },
  needs_review: { label: "Needs review", color: "#FF5C39" },
  delivered: { label: "Delivered", color: "#3a8a55" },
  regen_requested: { label: "Regen requested", color: "#C8553D" },
  revision_requested: { label: "Revision requested", color: "#C8553D" },
  closed: { label: "Closed", color: "#888" },
};

const STATUS_ORDER = ["paid_intake_pending", "intake_submitted", "generating", "needs_review", "delivered", "regen_requested", "revision_requested", "closed"];

function StatusPill({ status }) {
  const s = STATUS_LABELS[status] || { label: status, color: "#888" };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "4px 10px", borderRadius: 999,
      border: `1px solid ${s.color}`,
      color: s.color,
      background: "transparent",
      fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase",
      whiteSpace: "nowrap",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: s.color }}/>
      {s.label}
    </span>
  );
}

function AdminDashboard({ onOpenOrder }) {
  const [filter, setFilter] = React.useState("all");
  const [selectedOrder, setSelectedOrder] = React.useState(null);
  const filtered = filter === "all" ? SAMPLE_ORDERS : SAMPLE_ORDERS.filter(o => o.status === filter);

  const total = SAMPLE_ORDERS.length;
  const revenue = SAMPLE_ORDERS.reduce((s, o) => s + o.price, 0);
  const polished = SAMPLE_ORDERS.filter(o => o.tier === "Polished").length;
  const pending = SAMPLE_ORDERS.filter(o => ["needs_review", "generating", "intake_submitted", "paid_intake_pending"].includes(o.status)).length;

  if (selectedOrder) {
    return <AdminOrderDetail order={selectedOrder} onBack={() => setSelectedOrder(null)}/>;
  }

  return (
    <div style={{ minHeight: "100vh", background: "#0E0E0E", color: "#F5E9D7", fontFamily: "var(--f-sans)" }}>
      <div className="ij-admin-topbar" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 32px", borderBottom: "1px solid rgba(245,233,215,0.12)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <Logo color="#F5E9D7"/>
          <span className="chip" style={{ borderColor: "rgba(245,233,215,0.3)", color: "#F5E9D7" }}>ADMIN</span>
        </div>
        <div className="ij-admin-session" style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 13 }}>
          <span style={{ opacity: 0.6 }}>Logged in as</span>
          <strong>founder@insidejams.fm</strong>
          <button className="btn ghost small" style={{ color: "#F5E9D7", borderColor: "rgba(245,233,215,0.3)" }}>Sign out</button>
        </div>
      </div>

      {/* Metrics strip */}
      <div className="ij-admin-metrics" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderBottom: "1px solid rgba(245,233,215,0.12)" }}>
        {[
          { label: "Total orders", value: total, sub: "All time" },
          { label: "Revenue", value: `$${revenue}`, sub: "Gross, all time" },
          { label: "Quick / Polished", value: `${total - polished} / ${polished}`, sub: "Tier split" },
          { label: "Pending action", value: pending, sub: "Need review or generation" },
        ].map((m, i) => (
          <div className="ij-admin-metric" key={i} style={{ padding: "28px 32px", borderRight: i < 3 ? "1px solid rgba(245,233,215,0.12)" : "none" }}>
            <div className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>{m.label}</div>
            <div className="display" style={{ fontSize: 44, marginTop: 6 }}>{m.value}</div>
            <div style={{ fontSize: 12, opacity: 0.55, marginTop: 4 }}>{m.sub}</div>
          </div>
        ))}
      </div>

      <div style={{ padding: "32px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <h1 style={{ fontFamily: "var(--f-display)", fontSize: 40, margin: 0, fontStyle: "italic" }}>Orders</h1>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["all", "paid_intake_pending", "intake_submitted", "generating", "needs_review", "delivered"].map(f => (
              <button key={f} onClick={() => setFilter(f)} style={{
                padding: "8px 14px", borderRadius: 999,
                border: "1px solid " + (filter === f ? "#F5E9D7" : "rgba(245,233,215,0.2)"),
                background: filter === f ? "#F5E9D7" : "transparent",
                color: filter === f ? "#0E0E0E" : "#F5E9D7",
                fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.06em",
                textTransform: "uppercase", cursor: "pointer",
              }}>{f === "all" ? "All" : STATUS_LABELS[f]?.label || f}</button>
            ))}
          </div>
        </div>

        <div className="ij-admin-table-wrap" style={{ border: "1px solid rgba(245,233,215,0.12)", borderRadius: 12, overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "100px 1.5fr 1.6fr 1fr 1fr 170px 110px 80px", padding: "14px 20px", background: "rgba(245,233,215,0.04)", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", opacity: 0.6 }}>
            <span>Order</span><span>Recipient</span><span>Buyer</span><span>Type</span><span>Tier</span><span>Status</span><span>Created</span><span style={{ textAlign: "right" }}>$</span>
          </div>
          {filtered.map((o, i) => (
            <div key={o.id} onClick={() => {
              setSelectedOrder(o);
              if (onOpenOrder) onOpenOrder(o);
            }} style={{
              display: "grid", gridTemplateColumns: "100px 1.5fr 1.6fr 1fr 1fr 170px 110px 80px",
              padding: "16px 20px", alignItems: "center",
              borderTop: i === 0 ? "none" : "1px solid rgba(245,233,215,0.08)",
              cursor: "pointer", fontSize: 13.5,
              transition: "background 0.1s",
            }} onMouseEnter={e => e.currentTarget.style.background = "rgba(245,233,215,0.04)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 12, opacity: 0.7 }}>{o.id}</span>
              <span style={{ fontWeight: 600 }}>{o.name}</span>
              <span style={{ opacity: 0.7 }}>{o.buyer}</span>
              <span>{o.type}</span>
              <span>{o.tier}</span>
              <StatusPill status={o.status}/>
              <span style={{ opacity: 0.6, fontSize: 12 }}>{o.created}</span>
              <span style={{ textAlign: "right", fontFamily: "var(--f-mono)" }}>${o.price}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function AdminOrderDetail({ order = SAMPLE_ORDERS[0], onBack }) {
  const [status, setStatus] = React.useState(order.status);
  const [audioUrl, setAudioUrl] = React.useState("https://storage.insidejams.fm/audio/IJ-2046-v2.mp3");
  const [slug, setSlug] = React.useState("may-may-30");
  const [published, setPublished] = React.useState(false);
  const [deliveryQueued, setDeliveryQueued] = React.useState(false);
  const [lyrics, setLyrics] = React.useState("[Verse 1]\nShe rolls in twenty minutes late...\n\n[Chorus]\nMay-May, May-May...");
  const statusIndex = Math.max(0, STATUS_ORDER.indexOf(status));
  const fulfillment = [
    { label: "Intake in", done: STATUS_ORDER.indexOf(status) >= STATUS_ORDER.indexOf("intake_submitted") },
    { label: "Audio attached", done: Boolean(audioUrl.trim()) },
    { label: "Lyrics loaded", done: Boolean(lyrics.trim()) },
    { label: "Gift slug", done: Boolean(slug.trim()) },
    { label: "Published", done: published },
    { label: "Delivery email", done: deliveryQueued },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "#0E0E0E", color: "#F5E9D7" }}>
      <div className="ij-admin-detail-topbar" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 32px", borderBottom: "1px solid rgba(245,233,215,0.12)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button className="btn ghost small" onClick={onBack} style={{ color: "#F5E9D7", borderColor: "rgba(245,233,215,0.3)" }}>← All orders</button>
          <span style={{ fontFamily: "var(--f-mono)", fontSize: 12, opacity: 0.6 }}>{order.id} · created {order.created}</span>
        </div>
        <div className="ij-admin-detail-actions" style={{ display: "flex", gap: 8 }}>
          <a className="btn ghost small" href={`mailto:${order.buyer}`} style={{ color: "#F5E9D7", borderColor: "rgba(245,233,215,0.3)" }}>Email buyer</a>
          <button className="btn small" style={{ background: published ? "#3a8a55" : "var(--tangerine)", borderColor: published ? "#3a8a55" : "var(--tangerine)", color: "#fff" }} onClick={() => {
            if (!published) setPublished(true);
            else setDeliveryQueued(true);
          }}>
            {!published ? "Publish gift page" : deliveryQueued ? "Delivery email queued" : "Send delivery email"}
          </button>
        </div>
      </div>

      <div className="ij-admin-detail-shell" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", maxWidth: 1320, margin: "0 auto", padding: "32px", gap: 32 }}>
        {/* Left · fulfillment */}
        <div>
          <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.6 }}>Order</span>
          <h1 style={{ fontFamily: "var(--f-display)", fontSize: 48, margin: "8px 0 4px", fontStyle: "italic" }}>{order.tier} Jam for {order.name}</h1>
          <p style={{ opacity: 0.65, fontSize: 14 }}>{order.type} · {order.buyer} · ${order.price}</p>

          <div className="ij-admin-fulfillment-strip" style={{ marginTop: 18, display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 }}>
            {fulfillment.map(item => (
              <div key={item.label} style={{
                padding: "9px 10px",
                borderRadius: 10,
                border: `1px solid ${item.done ? "rgba(58,138,85,0.55)" : "rgba(245,233,215,0.16)"}`,
                background: item.done ? "rgba(58,138,85,0.12)" : "rgba(245,233,215,0.035)",
                color: item.done ? "#9bd0a8" : "#F5E9D7",
                fontFamily: "var(--f-mono)",
                fontSize: 9,
                letterSpacing: "0.06em",
                textTransform: "uppercase",
              }}>{item.done ? "OK " : ""}{item.label}</div>
            ))}
          </div>

          <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: `repeat(${STATUS_ORDER.length}, 1fr)`, gap: 6 }}>
            {STATUS_ORDER.map((s, i) => (
              <div key={s} title={STATUS_LABELS[s].label} style={{
                height: 7,
                borderRadius: 999,
                background: i <= statusIndex ? STATUS_LABELS[s].color : "rgba(245,233,215,0.12)",
                boxShadow: i === statusIndex ? `0 0 12px ${STATUS_LABELS[s].color}66` : "none",
              }}/>
            ))}
          </div>

          <div style={{ marginTop: 24, padding: 20, border: "1px solid rgba(245,233,215,0.15)", borderRadius: 12 }}>
            <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>Status</span>
            <div style={{ display: "flex", gap: 8, marginTop: 12, flexWrap: "wrap" }}>
              {Object.keys(STATUS_LABELS).map(s => (
                <button key={s} onClick={() => setStatus(s)} style={{
                  padding: "8px 12px", borderRadius: 999,
                  border: `1px solid ${status === s ? STATUS_LABELS[s].color : "rgba(245,233,215,0.18)"}`,
                  background: status === s ? STATUS_LABELS[s].color + "22" : "transparent",
                  color: status === s ? STATUS_LABELS[s].color : "#F5E9D7",
                  fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.06em",
                  textTransform: "uppercase", cursor: "pointer",
                }}>{STATUS_LABELS[s].label}</button>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 24, padding: 20, border: "1px solid rgba(245,233,215,0.15)", borderRadius: 12 }}>
            <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>Audio</span>
            <div style={{ marginTop: 12 }} className="field">
              <label style={{ color: "#F5E9D7", opacity: 0.6 }}>Audio URL</label>
              <input value={audioUrl} onChange={e => setAudioUrl(e.target.value)} style={{ background: "transparent", color: "#F5E9D7", borderColor: "rgba(245,233,215,0.2)" }}/>
            </div>
            <div style={{ marginTop: 12 }}>
              <AudioPlayer title="IJ-2046-v2.mp3" duration={54} accent="var(--tangerine)" seed={31} compact/>
            </div>
          </div>

          <div style={{ marginTop: 24, padding: 20, border: "1px solid rgba(245,233,215,0.15)", borderRadius: 12 }}>
            <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>Lyrics</span>
            <textarea value={lyrics} onChange={e => setLyrics(e.target.value)} style={{ width: "100%", marginTop: 12, padding: 14, minHeight: 200, background: "transparent", color: "#F5E9D7", border: "1px solid rgba(245,233,215,0.2)", borderRadius: 8, fontFamily: "var(--f-mono)", fontSize: 13, lineHeight: 1.6, resize: "vertical" }}/>
          </div>

          <div style={{ marginTop: 24, padding: 20, border: "1px solid rgba(245,233,215,0.15)", borderRadius: 12 }}>
            <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>Gift page</span>
            <div className="ij-admin-gift-fields" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 12 }}>
              <div className="field"><label style={{ color: "#F5E9D7", opacity: 0.6 }}>Slug</label><input value={slug} onChange={e => setSlug(e.target.value)} style={{ background: "transparent", color: "#F5E9D7", borderColor: "rgba(245,233,215,0.2)" }}/></div>
              <div className="field"><label style={{ color: "#F5E9D7", opacity: 0.6 }}>Cover template</label>
                <select style={{ background: "#0E0E0E", color: "#F5E9D7", borderColor: "rgba(245,233,215,0.2)" }}>
                  <option>Bold Colorful</option><option>Retro Album</option><option>Birthday Chaos</option><option>Heartfelt Minimal</option><option>Mixtape</option><option>Rap/Trap Mixtape</option>
                </select>
              </div>
            </div>
            <div style={{ marginTop: 12, fontFamily: "var(--f-mono)", fontSize: 12, opacity: 0.6 }}>
              Private page: insidejams.fm/jam/{slug || "pending-slug"}
            </div>
          </div>
        </div>

        {/* Right · intake answers */}
        <div>
          <div style={{ padding: 20, border: "1px solid rgba(245,233,215,0.15)", borderRadius: 12, position: "sticky", top: 20 }}>
            <span className="eyebrow" style={{ color: "#F5E9D7", opacity: 0.55 }}>Intake answers</span>
            <div style={{ marginTop: 14, fontSize: 13.5, lineHeight: 1.6 }}>
              {[
                ["Recipient", "Maya 'May-May' Chen"],
                ["Pronunciation", "MAY-uh"],
                ["Relationship", "Best friend"],
                ["Occasion", "30th birthday · May 14"],
                ["Genre", "Pop anthem"],
                ["Tone", "Medium roast"],
                ["Traits", "1) Always 20 min late · 2) Texts in all caps · 3) Insists she's an introvert"],
                ["Story", "Cancun trip · lost shoes in the ocean and refused to admit it"],
                ["Hobby", "Selling out at hot girl walks"],
                ["Off-limits", "Her dad's recent surgery"],
                ["Secret greatness", "She remembers every birthday and shows up for everyone"],
                ["Things to avoid", "Anything about her ex"],
                ["Sender message", `"Happy 30th, weirdo. You deserve to be sung about."`],
              ].map(([k,v]) => (
                <div key={k} style={{ display: "grid", gridTemplateColumns: "110px 1fr", gap: 12, padding: "10px 0", borderBottom: "1px solid rgba(245,233,215,0.08)" }}>
                  <span style={{ fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.55, letterSpacing: "0.06em", textTransform: "uppercase" }}>{k}</span>
                  <span>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 14, padding: 12, background: "rgba(58,138,85,0.12)", border: "1px solid rgba(58,138,85,0.3)", borderRadius: 8, fontSize: 12, color: "#9bd0a8" }}>
              Content boundaries confirmed
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminDashboard, AdminOrderDetail, SAMPLE_ORDERS });
