/* global React, useRoute, useToast, I */
const { useState: usePanelState, useMemo: usePanelMemo, useEffect: usePanelEffect } = React;

/* ─────────────────────────────────────────────────────────────────
   VIEWS Panel — the studio's social-first service marketplace.
   Member-only inside the portal. Catalog is editable here; live
   transactions route through /api/checkout (Stripe Checkout).
   ───────────────────────────────────────────────────────────────── */

const PANEL_GROWTH = [
  { id: "ig-vetted",  platform: "Instagram", name: "Vetted Followers",     metric: "followers", rate: 29,  min: 100,  max: 50000,  refill: true,  delivery: "1–3 days",  note: "Aged accounts · 90-day refill" },
  { id: "ig-engaged", platform: "Instagram", name: "Engaged Followers",    metric: "followers", rate: 89,  min: 100,  max: 25000,  refill: true,  delivery: "3–7 days",  note: "Niche-matched · will engage 14 days" },
  { id: "ig-likes",   platform: "Instagram", name: "Post Likes",           metric: "likes",     rate: 9,   min: 50,   max: 20000,  refill: true,  delivery: "24 hours",  note: "Refill protected" },
  { id: "ig-reels",   platform: "Instagram", name: "Reel Views (Ad-Driven)", metric: "views",   rate: 19,  min: 500,  max: 500000, refill: false, delivery: "24 hours",  note: "Real Meta ad spend · no bot risk" },
  { id: "tt-followers", platform: "TikTok",  name: "Followers",            metric: "followers", rate: 34,  min: 100,  max: 100000, refill: true,  delivery: "1–3 days",  note: "Real users · refill backed" },
  { id: "tt-views",   platform: "TikTok",    name: "Video Views",          metric: "views",     rate: 9,   min: 1000, max: 1000000, refill: false, delivery: "12 hours", note: "Geo-targeted available" },
  { id: "yt-subs",    platform: "YouTube",   name: "Subscribers (Real)",   metric: "subscribers", rate: 79, min: 50,  max: 10000,  refill: true,  delivery: "3–7 days",  note: "Watch-through verified" },
  { id: "yt-views",   platform: "YouTube",   name: "Video Views",          metric: "views",     rate: 24,  min: 500,  max: 500000, refill: false, delivery: "2–5 days",  note: "Music-video ready" },
  { id: "x-followers",platform: "X",         name: "Followers",            metric: "followers", rate: 39,  min: 100,  max: 25000,  refill: true,  delivery: "1–3 days",  note: "Targeted by niche" },
];

const PANEL_DESIGN = [
  { id: "d-profile",   name: "Profile Refresh",        desc: "Bio rewrite · profile photo edit · highlight covers", price: 149, delivery: "3 days" },
  { id: "d-content",   name: "Content Pack — 10 Posts", desc: "Custom-designed feed posts in your brand style",     price: 349, delivery: "5 days" },
  { id: "d-stories",   name: "Story Template Set",     desc: "15 reusable branded story templates",                price: 199, delivery: "4 days" },
  { id: "d-brand",     name: "Logo & Brand Kit",       desc: "Logo · palette · typography · usage guide",          price: 549, delivery: "7 days", popular: true },
  { id: "d-management",name: "Account Management · 30d", desc: "Posting · engagement · hashtag strategy · growth report", price: 899, delivery: "Ongoing" },
];

const PANEL_INDUSTRY = [
  { id: "i-playlist",   name: "Curated Playlist Placement", desc: "Real curators · streaming guarantees", price: 449, delivery: "10–14 days" },
  { id: "i-spotify",    name: "Spotify Editorial Pitch Prep", desc: "Pitch sheet · metadata · release strategy", price: 299, delivery: "5 days" },
  { id: "i-tiktok",     name: "TikTok Creator Campaign", desc: "Real creators · real reach · usage rights", price: 1499, delivery: "14 days", popular: true },
  { id: "i-press",      name: "Press Release + Blog Pitch", desc: "Drafted, distributed, tracked", price: 599, delivery: "7 days" },
  { id: "i-podcast",    name: "Podcast Booking", desc: "Booked guest spots on niche-relevant shows", price: 749, delivery: "21 days" },
  { id: "i-sync",       name: "Sync Licensing Pitch", desc: "Curated to TV / film / ad sync teams", price: 399, delivery: "7 days" },
];

const PANEL_PACKAGES = [
  { id: "pkg-launch",   name: "The Launch",  desc: "New artist debut. Brand kit + 10 content + 30-day management + Spotify prep.", price: 1299, badge: "Best for new artists" },
  { id: "pkg-era",      name: "The Era",     desc: "Single / EP rollout. Brand · content · TikTok creators · press · pre-save tools.", price: 2999, badge: "Most popular" },
  { id: "pkg-empire",   name: "The Empire",  desc: "Concierge retainer. Everything on-tap, monthly. Includes priority Atlas concierge.", price: 4999, badge: "Concierge", recurring: true },
];

const PANEL_TABS = [
  { key: "atelier",  label: "Atelier",  blurb: "Vetted growth — boutique pricing on the studio's hand-picked services." },
  { key: "industry", label: "Industry", blurb: "Music-industry services that move careers, not just numbers." },
  { key: "studio",   label: "Studio",   blurb: "Design and account management, fulfilled by the studio." },
  { key: "packages", label: "Packages", blurb: "Three signature bundles — pick the moment, we run the play." },
];

function PanelHero() {
  return (
    <section className="container" style={{ paddingTop: 72, paddingBottom: 32 }}>
      <span className="eyebrow eyebrow-gold">§ VIEWS · The studio panel</span>
      <h1 className="serif balance" style={{ fontSize: "clamp(48px, 7vw, 96px)", lineHeight: 0.96, letterSpacing: "-0.02em", margin: "16px 0 22px", maxWidth: 1100 }}>
        Real reach.<br/><em style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>Real design.</em>
      </h1>
      <p className="pretty" style={{ color: "var(--text-1)", fontSize: 16, lineHeight: 1.65, maxWidth: 640, margin: 0 }}>
        Pick a service, set a quantity, drop the link. The studio handles delivery, design, and the optimization that keeps you growing after. Member-only inside the portal — boutique rates, loyalty credits per order.
      </p>
    </section>
  );
}

function PriceTag({ amount, suffix }) {
  return (
    <span style={{ fontFamily: "var(--mono)", fontWeight: 700, color: "var(--gold)", fontSize: 16 }}>
      ${amount}{suffix && <span style={{ color: "var(--text-3)", fontWeight: 500, fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", marginLeft: 6 }}>{suffix}</span>}
    </span>
  );
}

function GrowthRow({ s, onPick }) {
  return (
    <button onClick={() => onPick(s)} style={{
      width: "100%", textAlign: "left", background: "#0c0c0c", border: "1px solid var(--border)",
      borderRadius: 12, padding: "18px 20px", cursor: "pointer", display: "grid",
      gridTemplateColumns: "auto 1fr auto", gap: 18, alignItems: "center",
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--gold)"}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border)"}>
      <span style={{ width: 44, height: 44, borderRadius: 10, background: "#0a0a0a", border: "1px solid var(--border-1)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.1em", color: "var(--gold)" }}>{s.platform.slice(0, 2).toUpperCase()}</span>
      <div style={{ minWidth: 0 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 4 }}>{s.platform}</div>
        <div className="serif" style={{ fontSize: 18, color: "var(--text-1)", lineHeight: 1.1 }}>{s.name}</div>
        <div className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.05em", marginTop: 6 }}>{s.delivery} · {s.note}{s.refill ? " · refill" : ""}</div>
      </div>
      <PriceTag amount={s.rate} suffix="per 1k" />
    </button>
  );
}

function FlatRow({ s, onAdd, popular }) {
  return (
    <article style={{
      background: "#0c0c0c", border: `1px solid ${popular ? "var(--gold)" : "var(--border)"}`,
      borderRadius: 12, padding: 24, display: "flex", flexDirection: "column", gap: 14,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start", gap: 12 }}>
        <div>
          <div className="serif" style={{ fontSize: 22, lineHeight: 1.1 }}>{s.name}</div>
          <div style={{ fontSize: 13, color: "var(--text-2)", marginTop: 4, lineHeight: 1.5 }}>{s.desc}</div>
        </div>
        <PriceTag amount={s.price} />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 8, borderTop: "1px solid var(--border-1)" }}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", color: "var(--text-3)" }}>{s.delivery}</span>
        <button className="btn btn-line" style={{ padding: "8px 14px", fontSize: 12 }} onClick={() => onAdd(s)}>
          Add to cart <I name="plus" size={12} />
        </button>
      </div>
    </article>
  );
}

function GrowthSheet({ service, onClose, onAdd }) {
  const [quantity, setQuantity] = usePanelState(service.min);
  const [target, setTarget] = usePanelState("");
  const total = ((quantity / 1000) * service.rate).toFixed(2);
  const valid = target.trim() && quantity >= service.min && quantity <= service.max;

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(0,0,0,0.7)", backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "#0a0a0a", border: "1px solid var(--border)", borderRadius: 16,
        padding: 28, maxWidth: 480, width: "100%", maxHeight: "90vh", overflowY: "auto",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start", marginBottom: 20 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 4 }}>{service.platform}</div>
            <h2 className="serif" style={{ fontSize: 28, lineHeight: 1.05, margin: 0 }}>{service.name}</h2>
          </div>
          <button onClick={onClose} className="icon-btn" style={{ width: 32, height: 32, border: "1px solid var(--border)", borderRadius: 999, background: "transparent" }}>
            <I name="close" size={14} />
          </button>
        </div>

        <div style={{ display: "grid", gap: 18 }}>
          <div>
            <label className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase", display: "block", marginBottom: 8 }}>Target URL</label>
            <input
              type="url"
              value={target}
              onChange={(e) => setTarget(e.target.value)}
              placeholder="https://instagram.com/yourhandle"
              className="input"
              style={{ width: "100%", fontFamily: "var(--mono)", fontSize: 13 }}
            />
          </div>
          <div>
            <label className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase", display: "block", marginBottom: 8 }}>
              Quantity · min {service.min.toLocaleString()} / max {service.max.toLocaleString()}
            </label>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="icon-btn" style={{ width: 44, height: 44, border: "1px solid var(--border)", borderRadius: 10 }} onClick={() => setQuantity(Math.max(service.min, quantity - 100))}><I name="minus" size={14} /></button>
              <input
                type="number"
                value={quantity}
                onChange={(e) => {
                  const v = parseInt(e.target.value) || service.min;
                  setQuantity(Math.min(service.max, Math.max(service.min, v)));
                }}
                className="input"
                style={{ flex: 1, textAlign: "center", fontFamily: "var(--mono)", fontWeight: 700, fontSize: 18 }}
              />
              <button className="icon-btn" style={{ width: 44, height: 44, border: "1px solid var(--border)", borderRadius: 10 }} onClick={() => setQuantity(Math.min(service.max, quantity + 100))}><I name="plus" size={14} /></button>
            </div>
            <input
              type="range"
              min={service.min}
              max={service.max}
              step={Math.max(1, Math.floor((service.max - service.min) / 100))}
              value={quantity}
              onChange={(e) => setQuantity(parseInt(e.target.value))}
              style={{ width: "100%", marginTop: 12, accentColor: "var(--gold)" }}
            />
          </div>
          <div style={{ borderTop: "1px solid var(--border-1)", paddingTop: 18, display: "flex", justifyContent: "space-between", alignItems: "end" }}>
            <div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 6 }}>Total</div>
              <div className="serif" style={{ fontSize: 36, color: "var(--gold)", fontStyle: "italic", lineHeight: 1 }}>${total}</div>
            </div>
            <div className="mono" style={{ fontSize: 10, color: "var(--text-3)", letterSpacing: "0.1em", textAlign: "right" }}>
              {service.delivery}{service.refill && <><br/><span style={{ color: "var(--gold)" }}>↻ Refill</span></>}
            </div>
          </div>
          <button
            className="btn btn-gold btn-lg"
            disabled={!valid}
            style={{ opacity: valid ? 1 : 0.5 }}
            onClick={() => {
              onAdd({
                id: `growth-${service.id}-${Date.now()}`,
                kind: "growth",
                serviceId: service.id,
                name: `${service.platform} · ${service.name}`,
                target,
                quantity,
                price: parseFloat(total),
                delivery: service.delivery,
              });
              onClose();
            }}
          >
            Add to cart <I name="arrow" size={14} />
          </button>
        </div>
      </div>
    </div>
  );
}

function CartDrawer({ open, items, onClose, onRemove, onCheckout, busy }) {
  if (!open) return null;
  const total = items.reduce((s, x) => s + (x.price || 0), 0);
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 110, background: "rgba(0,0,0,0.7)", backdropFilter: "blur(8px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "#0a0a0a", border: "1px solid var(--border)", borderRadius: 16, padding: 28, maxWidth: 480, width: "100%", maxHeight: "90vh", overflowY: "auto", display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <h2 className="serif" style={{ fontSize: 28, margin: 0 }}>Your order</h2>
          <button onClick={onClose} className="icon-btn" style={{ width: 32, height: 32, border: "1px solid var(--border)", borderRadius: 999, background: "transparent" }}>
            <I name="close" size={14} />
          </button>
        </div>
        {items.length === 0 ? (
          <div style={{ padding: "60px 0", textAlign: "center", color: "var(--text-2)" }}>
            <p className="serif" style={{ fontSize: 22 }}>Cart is empty.</p>
          </div>
        ) : (
          <>
            <div style={{ flex: 1, display: "grid", gap: 12, marginBottom: 18 }}>
              {items.map((item) => (
                <div key={item.id} style={{ background: "#0c0c0c", border: "1px solid var(--border-1)", borderRadius: 10, padding: 14 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
                    <div style={{ minWidth: 0 }}>
                      <div className="mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 4 }}>
                        {item.kind === "growth" ? "Growth" : item.kind === "design" ? "Studio" : item.kind === "industry" ? "Industry" : "Package"}
                      </div>
                      <div className="serif" style={{ fontSize: 15 }}>{item.name}</div>
                      {item.kind === "growth" && (
                        <div className="mono" style={{ fontSize: 11, color: "var(--text-2)", marginTop: 4 }}>{item.quantity.toLocaleString()} · {item.target}</div>
                      )}
                    </div>
                    <div style={{ textAlign: "right", flexShrink: 0 }}>
                      <PriceTag amount={item.price.toFixed(2)} />
                      <button onClick={() => onRemove(item.id)} className="lk" style={{ fontSize: 10, marginTop: 6, display: "block", textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-3)", background: "transparent", border: 0, cursor: "pointer" }}>Remove</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ paddingTop: 18, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase" }}>Total</span>
              <span className="serif" style={{ fontSize: 32, color: "var(--gold)", fontStyle: "italic" }}>${total.toFixed(2)}</span>
            </div>
            <button className="btn btn-gold btn-lg" onClick={onCheckout} disabled={busy} style={{ opacity: busy ? 0.5 : 1, width: "100%" }}>
              {busy ? "Opening checkout…" : "Continue to checkout"} <I name="arrow" size={14} />
            </button>
          </>
        )}
      </div>
    </div>
  );
}

function Panel() {
  const toast = useToast();
  const [tab, setTab] = usePanelState("atelier");
  const [platform, setPlatform] = usePanelState("All");
  const [picked, setPicked] = usePanelState(null);
  const [cart, setCart] = usePanelState([]);
  const [cartOpen, setCartOpen] = usePanelState(false);
  const [busy, setBusy] = usePanelState(false);

  const platforms = ["All", "Instagram", "TikTok", "YouTube", "X"];
  const growthFiltered = platform === "All" ? PANEL_GROWTH : PANEL_GROWTH.filter((s) => s.platform === platform);

  function addItem(item) {
    setCart((c) => [...c, item]);
    toast(`Added · ${item.name}`);
  }
  function removeItem(id) {
    setCart((c) => c.filter((x) => x.id !== id));
  }

  async function checkout() {
    if (cart.length === 0 || busy) return;
    setBusy(true);
    try {
      const r = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items: cart, mode: "payment" }),
      });
      const data = await r.json();
      if (data.url) {
        window.location.assign(data.url);
        return;
      }
      throw new Error(data.error || "checkout_failed");
    } catch (err) {
      toast("Checkout error — try again or contact studio@elevenviews.io.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className="fade">
      <PanelHero />

      <hr className="rule" />

      {/* Tabs */}
      <section className="container" style={{ paddingTop: 32, paddingBottom: 16 }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {PANEL_TABS.map((t) => (
            <button key={t.key} className="chip" data-active={tab === t.key} onClick={() => setTab(t.key)} style={{ padding: "10px 16px" }}>
              {t.label}
            </button>
          ))}
        </div>
        <p style={{ fontSize: 14, color: "var(--text-2)", margin: "18px 0 0", maxWidth: 640 }}>
          {PANEL_TABS.find((x) => x.key === tab)?.blurb}
        </p>
      </section>

      {/* Body */}
      <section className="container" style={{ paddingTop: 24, paddingBottom: 96 }}>
        {tab === "atelier" && (
          <>
            <div style={{ display: "flex", gap: 6, marginBottom: 18, flexWrap: "wrap" }}>
              {platforms.map((p) => (
                <button key={p} className="chip" data-active={platform === p} onClick={() => setPlatform(p)} style={{ padding: "8px 14px", fontSize: 11 }}>{p}</button>
              ))}
            </div>
            <div style={{ display: "grid", gap: 12 }}>
              {growthFiltered.map((s) => (
                <GrowthRow key={s.id} s={s} onPick={setPicked} />
              ))}
            </div>
          </>
        )}

        {tab === "industry" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
            {PANEL_INDUSTRY.map((s) => (
              <FlatRow key={s.id} s={s} popular={s.popular} onAdd={(svc) => addItem({
                id: `industry-${svc.id}-${Date.now()}`, kind: "industry", serviceId: svc.id,
                name: svc.name, price: svc.price, delivery: svc.delivery,
              })} />
            ))}
          </div>
        )}

        {tab === "studio" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
            {PANEL_DESIGN.map((s) => (
              <FlatRow key={s.id} s={s} popular={s.popular} onAdd={(svc) => addItem({
                id: `design-${svc.id}-${Date.now()}`, kind: "design", serviceId: svc.id,
                name: svc.name, price: svc.price, delivery: svc.delivery,
              })} />
            ))}
          </div>
        )}

        {tab === "packages" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
            {PANEL_PACKAGES.map((s) => (
              <article key={s.id} style={{ background: "#0c0c0c", border: "1px solid var(--gold)", borderRadius: 14, padding: 28, display: "flex", flexDirection: "column", gap: 14 }}>
                {s.badge && <span className="num" style={{ background: "var(--gold)", color: "#000", padding: "4px 8px", borderRadius: 3, fontWeight: 600, alignSelf: "start" }}>{s.badge}</span>}
                <div className="serif" style={{ fontSize: 30, lineHeight: 1.05 }}>{s.name}</div>
                <p style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.55, margin: 0 }}>{s.desc}</p>
                <div style={{ marginTop: "auto", display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 14, borderTop: "1px solid var(--border-1)" }}>
                  <PriceTag amount={s.price} suffix={s.recurring ? "/mo" : ""} />
                  <button className="btn btn-gold" style={{ padding: "10px 18px" }} onClick={() => addItem({
                    id: `pkg-${s.id}-${Date.now()}`, kind: "package", serviceId: s.id,
                    name: s.name, price: s.price, recurring: s.recurring,
                  })}>
                    Add <I name="plus" size={12} />
                  </button>
                </div>
              </article>
            ))}
          </div>
        )}
      </section>

      {/* Sticky cart bar */}
      {cart.length > 0 && (
        <button onClick={() => setCartOpen(true)} className="btn btn-gold btn-lg" style={{
          position: "fixed", bottom: 24, left: 24, right: 24, maxWidth: 560, margin: "0 auto",
          zIndex: 50, justifyContent: "space-between", display: "flex", padding: "14px 22px",
          boxShadow: "0 12px 40px rgba(0,0,0,0.6)",
        }}>
          <span><I name="bag" size={14} /> {cart.length} {cart.length === 1 ? "item" : "items"}</span>
          <span style={{ fontFamily: "var(--mono)" }}>${cart.reduce((s, x) => s + x.price, 0).toFixed(2)} <I name="arrow" size={14} /></span>
        </button>
      )}

      {/* Modals */}
      {picked && <GrowthSheet service={picked} onClose={() => setPicked(null)} onAdd={addItem} />}
      <CartDrawer open={cartOpen} items={cart} onClose={() => setCartOpen(false)} onRemove={removeItem} onCheckout={checkout} busy={busy} />
    </main>
  );
}

window.Panel = Panel;
window.PANEL_GROWTH = PANEL_GROWTH;
window.PANEL_DESIGN = PANEL_DESIGN;
window.PANEL_INDUSTRY = PANEL_INDUSTRY;
window.PANEL_PACKAGES = PANEL_PACKAGES;
