"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { EmptyState } from "@/components/ui/empty-state";
import { useToast } from "@/components/ui/toast";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { cn, formatCurrency, formatDate } from "@/lib/utils";
import {
  BOOKING_STATUSES,
  CONTACT_ROLES,
  RELEASE_STATUSES,
  RELEASE_TYPES,
  type ArtistSlug,
  type BookingStatus,
  type ContactRole,
  type MusicBooking,
  type MusicContact,
  type MusicRelease,
  type ReleaseStatus,
  type ReleaseType,
  type SplitShare,
  type StreamingSnapshot,
} from "@/lib/music/types";
import { seedSocialDraftIfMissing } from "@/lib/music/release-to-social";

type Tab = "releases" | "bookings" | "contacts" | "streaming";

const TABS: { id: Tab; label: string; icon: string }[] = [
  { id: "releases", label: "Releases", icon: "💿" },
  { id: "bookings", label: "Bookings", icon: "🎤" },
  { id: "contacts", label: "Contacts", icon: "📇" },
  { id: "streaming", label: "Streaming", icon: "📈" },
];

const RELEASE_STATUS_TONE: Record<
  ReleaseStatus,
  "outline" | "info" | "success" | "destructive" | "warning"
> = {
  Concept: "outline",
  Recording: "info",
  Mixing: "info",
  Mastering: "info",
  "Distribution Submitted": "warning",
  Released: "success",
  Postponed: "warning",
  Shelved: "destructive",
};

const BOOKING_STATUS_TONE: Record<
  BookingStatus,
  "outline" | "info" | "success" | "destructive" | "warning"
> = {
  Inquiry: "outline",
  Held: "warning",
  "Contract Sent": "info",
  Confirmed: "info",
  Performed: "success",
  Paid: "success",
  Cancelled: "destructive",
};

export function MusicWorkspace({ artistSlug }: { artistSlug: ArtistSlug }) {
  const org = ALL_ORGANIZATIONS.find((o) => o.slug === artistSlug);
  const [tab, setTab] = useState<Tab>("releases");
  // Lazy-mount tab panels: only render a panel after its tab has been visited
  // at least once. Once mounted, we keep the panel in the tree and toggle
  // visibility with `hidden` / `block` so state (form drafts, scroll position)
  // is preserved across tab switches.
  const [visited, setVisited] = useState<Set<Tab>>(() => new Set<Tab>(["releases"]));

  if (!org) return null;

  return (
    <div className="space-y-6 max-w-5xl">
      <Card>
        <CardContent className="p-5">
          <div className="flex items-start gap-4 flex-wrap">
            <div
              className="w-16 h-16 rounded-xl flex items-center justify-center text-4xl shrink-0"
              style={{ backgroundColor: `${org.primaryColor}25` }}
            >
              {org.emoji}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap mb-1">
                {artistSlug === "riich-villainz" && (
                  <Badge variant="warning">Label · 49% owned</Badge>
                )}
                {artistSlug === "dj-ricoveli" && (
                  <>
                    <Badge variant="info">SAG subsidiary</Badge>
                    <Badge variant="outline">Recording + DJ</Badge>
                  </>
                )}
                <Badge variant="outline">{org.industry}</Badge>
                <Badge variant="outline">{org.state}</Badge>
              </div>
              <h2 className="text-xl font-semibold">{org.name}</h2>
              <p className="text-sm italic text-muted-foreground">{org.tagline}</p>
              <p className="mt-2 text-sm text-foreground/85">{org.blurb}</p>
            </div>
            <div className="flex flex-col gap-2 shrink-0">
              <Button asChild variant="outline" size="sm">
                <Link href="/app/music">← All artists</Link>
              </Button>
              <Button asChild variant="outline" size="sm">
                <Link href={`/app/social?entity=${artistSlug}`}>Social calendar</Link>
              </Button>
              <Button asChild variant="outline" size="sm">
                <Link href={`/portfolio/${artistSlug}`}>Public bio</Link>
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-2 flex items-center gap-1 flex-wrap">
          {TABS.map((t) => (
            <button
              key={t.id}
              onClick={() => {
                setTab(t.id);
                setVisited((prev) => {
                  if (prev.has(t.id)) return prev;
                  const next = new Set(prev);
                  next.add(t.id);
                  return next;
                });
              }}
              className={`text-sm px-3 py-1.5 rounded-md inline-flex items-center gap-1.5 transition-colors ${
                tab === t.id
                  ? "bg-foreground text-background"
                  : "text-muted-foreground hover:bg-accent"
              }`}
            >
              <span>{t.icon}</span>
              {t.label}
            </button>
          ))}
        </CardContent>
      </Card>

      {visited.has("releases") && (
        <div className={cn(tab === "releases" ? "block" : "hidden")}>
          <ReleasesTab artistSlug={artistSlug} />
        </div>
      )}
      {visited.has("bookings") && (
        <div className={cn(tab === "bookings" ? "block" : "hidden")}>
          <BookingsTab artistSlug={artistSlug} />
        </div>
      )}
      {visited.has("contacts") && (
        <div className={cn(tab === "contacts" ? "block" : "hidden")}>
          <ContactsTab artistSlug={artistSlug} />
        </div>
      )}
      {visited.has("streaming") && (
        <div className={cn(tab === "streaming" ? "block" : "hidden")}>
          <StreamingTab artistSlug={artistSlug} />
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Releases
// ──────────────────────────────────────────────────────────────────────────

function ReleasesTab({ artistSlug }: { artistSlug: ArtistSlug }) {
  const [all, setAll] = useLocalStorage<MusicRelease[]>("sag.music.releases", []);
  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const { toast } = useToast();
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const list = useMemo(
    () =>
      all
        .filter((r) => r.artistSlug === artistSlug)
        .sort((a, b) => b.releaseDate.localeCompare(a.releaseDate)),
    [all, artistSlug]
  );

  /**
   * Side-effect hook for the "Released" transition. Called from every code
   * path that can mutate a release's status — keeps the social-draft seeding
   * logic in one place.
   */
  function handleReleasedTransition(prev: MusicRelease | undefined, next: MusicRelease) {
    if (next.status !== "Released") return;
    if (prev && prev.status === "Released") return;
    const wrote = seedSocialDraftIfMissing(next);
    if (wrote) {
      toast({
        title: "Draft social post created",
        description: "View on /app/social",
        variant: "info",
        action: (
          <Link
            href="/app/social"
            className="text-xs font-medium underline text-blue-700 dark:text-blue-300"
          >
            Open social
          </Link>
        ),
      });
    }
  }

  function upsert(r: MusicRelease) {
    const existing = all.find((x) => x.id === r.id);
    handleReleasedTransition(existing, r);
    setAll((prev) => {
      const idx = prev.findIndex((x) => x.id === r.id);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = r;
        return copy;
      }
      return [...prev, r];
    });
  }

  function add(r: Omit<MusicRelease, "id" | "createdAt">) {
    const id = `rel-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
    upsert({ ...r, id, createdAt: new Date().toISOString() });
    setShowAdd(false);
  }

  async function remove(id: string) {
    const ok = await confirmAlert({
      title: "Delete this release?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    setAll((prev) => prev.filter((r) => r.id !== id));
  }

  const editing = editingId ? all.find((r) => r.id === editingId) : undefined;

  return (
    <>
    <div className="space-y-4">
      <Card>
        <CardContent className="p-4 flex items-center flex-wrap gap-2">
          <span className="text-sm font-medium">{list.length} release{list.length === 1 ? "" : "s"}</span>
          <Button
            size="sm"
            variant="brand"
            className="ml-auto"
            onClick={() => {
              setShowAdd((v) => !v);
              setEditingId(null);
            }}
          >
            {showAdd ? "Cancel" : "+ Add release"}
          </Button>
        </CardContent>
      </Card>

      {(showAdd || editing) && (
        <ReleaseForm
          artistSlug={artistSlug}
          initial={editing}
          onSave={(r) => {
            if (editing) {
              upsert({ ...editing, ...r });
              setEditingId(null);
            } else {
              add(r);
            }
          }}
          onCancel={() => {
            setShowAdd(false);
            setEditingId(null);
          }}
        />
      )}

      {list.length === 0 ? (
        <EmptyState
          icon="💿"
          title="No releases tracked yet"
          description="Track singles, EPs, albums, mixtapes, remixes. Royalty splits captured per release."
          size="compact"
        />
      ) : (
        list.map((r) => (
          <Card key={r.id}>
            <CardContent className="p-4">
              <div className="flex items-start gap-3 flex-wrap">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <Badge variant={RELEASE_STATUS_TONE[r.status]}>{r.status}</Badge>
                    <Badge variant="outline">{r.type}</Badge>
                    <span className="text-xs text-muted-foreground">
                      {formatDate(r.releaseDate)}
                    </span>
                  </div>
                  <h3 className="text-base font-semibold">{r.title}</h3>
                  {r.platforms && (
                    <p className="text-xs text-muted-foreground mt-0.5">{r.platforms}</p>
                  )}
                  {(r.isrc || r.upc) && (
                    <p className="text-[11px] text-muted-foreground font-mono mt-0.5">
                      {r.isrc ? `ISRC: ${r.isrc}` : ""}
                      {r.isrc && r.upc ? " · " : ""}
                      {r.upc ? `UPC: ${r.upc}` : ""}
                    </p>
                  )}
                  {r.splits.length > 0 && (
                    <div className="mt-2">
                      <div className="section-label">
                        Splits
                      </div>
                      <div className="mt-1 flex flex-wrap gap-1">
                        {r.splits.map((s, i) => (
                          <Badge key={i} variant="outline" className="text-[10px]">
                            {s.holder} {s.percent}%
                            {s.role ? ` · ${s.role}` : ""}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                  {r.notes && (
                    <p className="mt-2 text-xs text-muted-foreground italic whitespace-pre-wrap">
                      {r.notes}
                    </p>
                  )}
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  <Button variant="ghost" size="sm" onClick={() => setEditingId(r.id)}>
                    Edit
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => remove(r.id)}>
                    ×
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function ReleaseForm({
  artistSlug,
  initial,
  onSave,
  onCancel,
}: {
  artistSlug: ArtistSlug;
  initial?: MusicRelease;
  onSave: (r: Omit<MusicRelease, "id" | "createdAt">) => void;
  onCancel: () => void;
}) {
  const [title, setTitle] = useState(initial?.title ?? "");
  const [type, setType] = useState<ReleaseType>(initial?.type ?? "Single");
  const [status, setStatus] = useState<ReleaseStatus>(initial?.status ?? "Concept");
  const [releaseDate, setReleaseDate] = useState(
    initial?.releaseDate ?? new Date().toISOString().slice(0, 10)
  );
  const [platforms, setPlatforms] = useState(initial?.platforms ?? "");
  const [isrc, setIsrc] = useState(initial?.isrc ?? "");
  const [upc, setUpc] = useState(initial?.upc ?? "");
  const [splits, setSplits] = useState<SplitShare[]>(initial?.splits ?? []);
  const [notes, setNotes] = useState(initial?.notes ?? "");

  function submit() {
    if (!title.trim()) {
      alert("Title required.");
      return;
    }
    onSave({
      artistSlug,
      title: title.trim(),
      type,
      status,
      releaseDate,
      platforms: platforms.trim() || undefined,
      isrc: isrc.trim() || undefined,
      upc: upc.trim() || undefined,
      splits: splits.filter((s) => s.holder && s.percent),
      notes: notes.trim() || undefined,
    });
  }

  function updateSplit(idx: number, patch: Partial<SplitShare>) {
    setSplits((prev) => prev.map((s, i) => (i === idx ? { ...s, ...patch } : s)));
  }

  const totalPct = splits.reduce((a, s) => a + s.percent, 0);

  return (
    <Card>
      <CardContent className="p-5 space-y-3">
        <h3 className="text-sm font-semibold">
          {initial ? "Edit release" : "Add release"}
        </h3>
        <div className="grid gap-3 md:grid-cols-2">
          <Field label="Title">
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="e.g. ‘Sandhills Heat’"
              required
            />
          </Field>
          <Field label="Type">
            <select
              value={type}
              onChange={(e) => setType(e.target.value as ReleaseType)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {RELEASE_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Status">
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value as ReleaseStatus)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {RELEASE_STATUSES.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Release date">
            <Input
              type="date"
              value={releaseDate}
              onChange={(e) => setReleaseDate(e.target.value)}
            />
          </Field>
          <Field label="Platforms (comma-separated)" className="md:col-span-2">
            <Input
              value={platforms}
              onChange={(e) => setPlatforms(e.target.value)}
              placeholder="Spotify, Apple Music, YouTube, SoundCloud, Bandcamp"
            />
          </Field>
          <Field label="ISRC (optional)">
            <Input
              value={isrc}
              onChange={(e) => setIsrc(e.target.value)}
              placeholder="USRC1234567"
            />
          </Field>
          <Field label="UPC (optional)">
            <Input
              value={upc}
              onChange={(e) => setUpc(e.target.value)}
              placeholder="123456789012"
            />
          </Field>
        </div>

        <div className="rounded-md border bg-muted/30 p-3">
          <div className="flex items-center justify-between mb-2 flex-wrap gap-2">
            <label className="text-xs font-semibold">
              Royalty splits
              <span
                className={`ml-2 ${
                  totalPct === 100
                    ? "text-green-700 dark:text-green-400"
                    : "text-yellow-700 dark:text-yellow-400"
                }`}
              >
                ({totalPct}%)
              </span>
            </label>
            <Button
              variant="outline"
              size="sm"
              type="button"
              onClick={() =>
                setSplits([...splits, { holder: "", percent: 0, role: "" }])
              }
            >
              + Add split
            </Button>
          </div>
          {splits.length === 0 && (
            <p className="text-[11px] text-muted-foreground">
              Add at least one split — typically artist + label + producer. Should sum to 100%.
            </p>
          )}
          <div className="space-y-2">
            {splits.map((s, i) => (
              <div key={i} className="grid gap-2 md:grid-cols-12 items-center">
                <Input
                  className="md:col-span-5"
                  value={s.holder}
                  onChange={(e) => updateSplit(i, { holder: e.target.value })}
                  placeholder="Holder (e.g. Ricoveli, Riich Villainz)"
                />
                <Input
                  className="md:col-span-3"
                  type="number"
                  step="0.01"
                  min="0"
                  max="100"
                  value={s.percent}
                  onChange={(e) =>
                    updateSplit(i, { percent: parseFloat(e.target.value) || 0 })
                  }
                  placeholder="0"
                />
                <Input
                  className="md:col-span-3"
                  value={s.role ?? ""}
                  onChange={(e) => updateSplit(i, { role: e.target.value })}
                  placeholder="Role (artist / label / producer)"
                />
                <button
                  type="button"
                  className="md:col-span-1 text-xs text-muted-foreground hover:text-destructive"
                  onClick={() => setSplits(splits.filter((_, j) => j !== i))}
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>

        <Field label="Notes (credits, samples, sample clearances)">
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={3}
            className="w-full rounded-md border border-input bg-background p-2 text-sm"
          />
        </Field>

        <div className="flex items-center justify-end gap-2">
          <Button variant="ghost" size="sm" onClick={onCancel}>
            Cancel
          </Button>
          <Button variant="brand" size="sm" onClick={submit}>
            {initial ? "Save changes" : "Add release"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Bookings
// ──────────────────────────────────────────────────────────────────────────

function BookingsTab({ artistSlug }: { artistSlug: ArtistSlug }) {
  const [all, setAll] = useLocalStorage<MusicBooking[]>("sag.music.bookings", []);
  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const list = useMemo(
    () =>
      all
        .filter((b) => b.artistSlug === artistSlug)
        .sort((a, b) => b.date.localeCompare(a.date)),
    [all, artistSlug]
  );

  function upsert(b: MusicBooking) {
    setAll((prev) => {
      const idx = prev.findIndex((x) => x.id === b.id);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = b;
        return copy;
      }
      return [...prev, b];
    });
  }

  function add(b: Omit<MusicBooking, "id" | "createdAt">) {
    const id = `bk-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
    upsert({ ...b, id, createdAt: new Date().toISOString() });
    setShowAdd(false);
  }

  async function remove(id: string) {
    const ok = await confirmAlert({
      title: "Delete this booking?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    setAll((prev) => prev.filter((b) => b.id !== id));
  }

  function setStatus(id: string, status: BookingStatus) {
    setAll((prev) => prev.map((b) => (b.id === id ? { ...b, status } : b)));
  }

  const editing = editingId ? all.find((b) => b.id === editingId) : undefined;
  const upcomingFee = list
    .filter(
      (b) => (b.status === "Confirmed" || b.status === "Contract Sent") && b.date >= new Date().toISOString().slice(0, 10)
    )
    .reduce((a, b) => a + b.fee, 0);

  return (
    <>
    <div className="space-y-4">
      <Card>
        <CardContent className="p-4 flex items-center flex-wrap gap-3">
          <span className="text-sm font-medium">{list.length} booking{list.length === 1 ? "" : "s"}</span>
          <span className="text-xs text-muted-foreground">
            Upcoming fee: {formatCurrency(upcomingFee)}
          </span>
          <Button
            size="sm"
            variant="brand"
            className="ml-auto"
            onClick={() => {
              setShowAdd((v) => !v);
              setEditingId(null);
            }}
          >
            {showAdd ? "Cancel" : "+ Add booking"}
          </Button>
        </CardContent>
      </Card>

      {(showAdd || editing) && (
        <BookingForm
          artistSlug={artistSlug}
          initial={editing}
          onSave={(b) => {
            if (editing) {
              upsert({ ...editing, ...b });
              setEditingId(null);
            } else {
              add(b);
            }
          }}
          onCancel={() => {
            setShowAdd(false);
            setEditingId(null);
          }}
        />
      )}

      {list.length === 0 ? (
        <EmptyState
          icon="🎤"
          title="No bookings yet"
          description="Track inquiries → contracts → performed → paid."
          size="compact"
        />
      ) : (
        list.map((b) => (
          <Card key={b.id}>
            <CardContent className="p-4">
              <div className="flex items-start gap-3 flex-wrap">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <Badge variant={BOOKING_STATUS_TONE[b.status]}>{b.status}</Badge>
                    <span className="text-xs text-muted-foreground">
                      {formatDate(b.date)}
                      {b.showTime ? ` · ${b.showTime}` : ""}
                    </span>
                    <span className="text-sm font-semibold tabular-nums">
                      {formatCurrency(b.fee)}
                    </span>
                    {b.deposit !== undefined && b.deposit > 0 && (
                      <span className="text-[11px] text-muted-foreground">
                        Deposit: {formatCurrency(b.deposit)}
                      </span>
                    )}
                  </div>
                  <h3 className="text-base font-semibold">{b.venue}</h3>
                  {b.location && (
                    <p className="text-xs text-muted-foreground">📍 {b.location}</p>
                  )}
                  {(b.bookerName || b.bookerEmail || b.bookerPhone) && (
                    <p className="mt-1 text-[11px] text-muted-foreground">
                      Booker:{" "}
                      {[b.bookerName, b.bookerEmail, b.bookerPhone]
                        .filter(Boolean)
                        .join(" · ")}
                    </p>
                  )}
                  {b.notes && (
                    <p className="mt-2 text-xs text-muted-foreground italic whitespace-pre-wrap">
                      {b.notes}
                    </p>
                  )}
                </div>
                <div className="flex flex-wrap items-center gap-1 shrink-0 w-full md:w-auto">
                  {b.status === "Inquiry" && (
                    <Button variant="outline" size="sm" onClick={() => setStatus(b.id, "Held")}>
                      Hold
                    </Button>
                  )}
                  {b.status === "Held" && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setStatus(b.id, "Contract Sent")}
                    >
                      Contract sent
                    </Button>
                  )}
                  {b.status === "Contract Sent" && (
                    <Button
                      variant="brand"
                      size="sm"
                      onClick={() => setStatus(b.id, "Confirmed")}
                    >
                      Confirm
                    </Button>
                  )}
                  {b.status === "Confirmed" && (
                    <Button
                      variant="brand"
                      size="sm"
                      onClick={() => setStatus(b.id, "Performed")}
                    >
                      Mark performed
                    </Button>
                  )}
                  {b.status === "Performed" && (
                    <Button variant="brand" size="sm" onClick={() => setStatus(b.id, "Paid")}>
                      Mark paid
                    </Button>
                  )}
                  <Button variant="ghost" size="sm" onClick={() => setEditingId(b.id)}>
                    Edit
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => remove(b.id)}>
                    ×
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function BookingForm({
  artistSlug,
  initial,
  onSave,
  onCancel,
}: {
  artistSlug: ArtistSlug;
  initial?: MusicBooking;
  onSave: (b: Omit<MusicBooking, "id" | "createdAt">) => void;
  onCancel: () => void;
}) {
  const [venue, setVenue] = useState(initial?.venue ?? "");
  const [location, setLocation] = useState(initial?.location ?? "");
  const [date, setDate] = useState(initial?.date ?? new Date().toISOString().slice(0, 10));
  const [showTime, setShowTime] = useState(initial?.showTime ?? "");
  const [fee, setFee] = useState(String(initial?.fee ?? ""));
  const [deposit, setDeposit] = useState(String(initial?.deposit ?? ""));
  const [status, setStatus] = useState<BookingStatus>(initial?.status ?? "Inquiry");
  const [bookerName, setBookerName] = useState(initial?.bookerName ?? "");
  const [bookerEmail, setBookerEmail] = useState(initial?.bookerEmail ?? "");
  const [bookerPhone, setBookerPhone] = useState(initial?.bookerPhone ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  function submit() {
    if (!venue.trim()) {
      alert("Venue required.");
      return;
    }
    const feeN = parseFloat(fee) || 0;
    onSave({
      artistSlug,
      venue: venue.trim(),
      location: location.trim() || undefined,
      date,
      showTime: showTime || undefined,
      fee: feeN,
      deposit: deposit ? parseFloat(deposit) : undefined,
      status,
      bookerName: bookerName.trim() || undefined,
      bookerEmail: bookerEmail.trim() || undefined,
      bookerPhone: bookerPhone.trim() || undefined,
      notes: notes.trim() || undefined,
    });
  }

  return (
    <Card>
      <CardContent className="p-5 space-y-3">
        <h3 className="text-sm font-semibold">
          {initial ? "Edit booking" : "Add booking"}
        </h3>
        <div className="grid gap-3 md:grid-cols-2">
          <Field label="Venue or event">
            <Input
              value={venue}
              onChange={(e) => setVenue(e.target.value)}
              placeholder="e.g. ‘Cat’s Cradle’"
              required
            />
          </Field>
          <Field label="Location (City, ST)">
            <Input
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              placeholder="Carrboro, NC"
            />
          </Field>
          <Field label="Date">
            <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
          </Field>
          <Field label="Show time (HH:MM)">
            <Input
              type="time"
              value={showTime}
              onChange={(e) => setShowTime(e.target.value)}
            />
          </Field>
          <Field label="Fee">
            <Input
              type="number"
              step="0.01"
              value={fee}
              onChange={(e) => setFee(e.target.value)}
              placeholder="0.00"
            />
          </Field>
          <Field label="Deposit received (optional)">
            <Input
              type="number"
              step="0.01"
              value={deposit}
              onChange={(e) => setDeposit(e.target.value)}
              placeholder="0.00"
            />
          </Field>
          <Field label="Status">
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value as BookingStatus)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {BOOKING_STATUSES.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Booker name">
            <Input
              value={bookerName}
              onChange={(e) => setBookerName(e.target.value)}
              placeholder="e.g. Frank Heath"
            />
          </Field>
          <Field label="Booker email">
            <Input
              type="email"
              value={bookerEmail}
              onChange={(e) => setBookerEmail(e.target.value)}
              placeholder="frank@catscradle.com"
            />
          </Field>
          <Field label="Booker phone">
            <Input
              type="tel"
              value={bookerPhone}
              onChange={(e) => setBookerPhone(e.target.value)}
              placeholder="(919) 555-0100"
            />
          </Field>
          <Field label="Notes (rider, parking, attendance)" className="md:col-span-2">
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={3}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
            />
          </Field>
        </div>
        <div className="flex items-center justify-end gap-2">
          <Button variant="ghost" size="sm" onClick={onCancel}>
            Cancel
          </Button>
          <Button variant="brand" size="sm" onClick={submit}>
            {initial ? "Save changes" : "Add booking"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Contacts
// ──────────────────────────────────────────────────────────────────────────

function ContactsTab({ artistSlug }: { artistSlug: ArtistSlug }) {
  const [all, setAll] = useLocalStorage<MusicContact[]>("sag.music.contacts", []);
  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const list = useMemo(
    () => all.filter((c) => c.artistSlug === artistSlug).sort((a, b) => a.name.localeCompare(b.name)),
    [all, artistSlug]
  );

  function add(c: Omit<MusicContact, "id" | "createdAt">) {
    const id = `ct-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
    setAll((prev) => [...prev, { ...c, id, createdAt: new Date().toISOString() }]);
    setShowAdd(false);
  }

  function update(id: string, patch: Partial<MusicContact>) {
    setAll((prev) => prev.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  }

  async function remove(id: string) {
    const ok = await confirmAlert({
      title: "Delete this contact?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    setAll((prev) => prev.filter((c) => c.id !== id));
  }

  const editing = editingId ? all.find((c) => c.id === editingId) : undefined;

  return (
    <>
    <div className="space-y-4">
      <Card>
        <CardContent className="p-4 flex items-center flex-wrap gap-2">
          <span className="text-sm font-medium">{list.length} contact{list.length === 1 ? "" : "s"}</span>
          <Button
            size="sm"
            variant="brand"
            className="ml-auto"
            onClick={() => {
              setShowAdd((v) => !v);
              setEditingId(null);
            }}
          >
            {showAdd ? "Cancel" : "+ Add contact"}
          </Button>
        </CardContent>
      </Card>

      {(showAdd || editing) && (
        <ContactForm
          artistSlug={artistSlug}
          initial={editing}
          onSave={(c) => {
            if (editing) {
              update(editing.id, c);
              setEditingId(null);
            } else {
              add(c);
            }
          }}
          onCancel={() => {
            setShowAdd(false);
            setEditingId(null);
          }}
        />
      )}

      {list.length === 0 ? (
        <EmptyState
          icon="📇"
          title="No contacts yet"
          description="Bookers, agents, producers, engineers, lawyers, distributors, PR."
          size="compact"
        />
      ) : (
        <div className="grid gap-3 md:grid-cols-2">
          {list.map((c) => (
            <Card key={c.id}>
              <CardContent className="p-4">
                <div className="flex items-start justify-between gap-2 mb-1">
                  <div className="min-w-0 flex-1">
                    <h3 className="text-base font-semibold">{c.name}</h3>
                    <div className="flex items-center gap-2 mt-0.5">
                      <Badge variant="outline">{c.role}</Badge>
                      {c.company && (
                        <span className="text-xs text-muted-foreground">{c.company}</span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <Button variant="ghost" size="sm" onClick={() => setEditingId(c.id)}>
                      Edit
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => remove(c.id)}>
                      ×
                    </Button>
                  </div>
                </div>
                {c.email && (
                  <div className="text-xs">
                    <a href={`mailto:${c.email}`} className="text-[var(--sag-brand)] hover:underline">
                      {c.email}
                    </a>
                  </div>
                )}
                {c.phone && (
                  <div className="text-xs">
                    <a href={`tel:${c.phone}`} className="text-[var(--sag-brand)] hover:underline">
                      {c.phone}
                    </a>
                  </div>
                )}
                {c.notes && (
                  <p className="mt-2 text-xs text-muted-foreground italic">{c.notes}</p>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function ContactForm({
  artistSlug,
  initial,
  onSave,
  onCancel,
}: {
  artistSlug: ArtistSlug;
  initial?: MusicContact;
  onSave: (c: Omit<MusicContact, "id" | "createdAt">) => void;
  onCancel: () => void;
}) {
  const [name, setName] = useState(initial?.name ?? "");
  const [role, setRole] = useState<ContactRole>(initial?.role ?? "Booker");
  const [company, setCompany] = useState(initial?.company ?? "");
  const [email, setEmail] = useState(initial?.email ?? "");
  const [phone, setPhone] = useState(initial?.phone ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  function submit() {
    if (!name.trim()) {
      alert("Name required.");
      return;
    }
    onSave({
      artistSlug,
      name: name.trim(),
      role,
      company: company.trim() || undefined,
      email: email.trim() || undefined,
      phone: phone.trim() || undefined,
      notes: notes.trim() || undefined,
    });
  }

  return (
    <Card>
      <CardContent className="p-5 space-y-3">
        <h3 className="text-sm font-semibold">
          {initial ? "Edit contact" : "Add contact"}
        </h3>
        <div className="grid gap-3 md:grid-cols-2">
          <Field label="Name">
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Full name"
              required
            />
          </Field>
          <Field label="Role">
            <select
              value={role}
              onChange={(e) => setRole(e.target.value as ContactRole)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {CONTACT_ROLES.map((r) => (
                <option key={r} value={r}>
                  {r}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Company">
            <Input
              value={company}
              onChange={(e) => setCompany(e.target.value)}
              placeholder="e.g. Cat’s Cradle"
            />
          </Field>
          <Field label="Email">
            <Input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="frank@example.com"
            />
          </Field>
          <Field label="Phone">
            <Input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="(919) 555-0100"
            />
          </Field>
          <Field label="Notes" className="md:col-span-2">
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={2}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
            />
          </Field>
        </div>
        <div className="flex items-center justify-end gap-2">
          <Button variant="ghost" size="sm" onClick={onCancel}>
            Cancel
          </Button>
          <Button variant="brand" size="sm" onClick={submit}>
            {initial ? "Save changes" : "Add contact"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Streaming snapshots
// ──────────────────────────────────────────────────────────────────────────

function StreamingTab({ artistSlug }: { artistSlug: ArtistSlug }) {
  const [all, setAll] = useLocalStorage<StreamingSnapshot[]>("sag.music.streaming", []);
  const { toast } = useToast();
  const current = useMemo(
    () => all.find((s) => s.artistSlug === artistSlug),
    [all, artistSlug]
  );
  const [draft, setDraft] = useState<StreamingSnapshot>(() => ({
    artistSlug,
    asOf: current?.asOf ?? new Date().toISOString().slice(0, 10),
    spotifyMonthlyListeners: current?.spotifyMonthlyListeners,
    spotifyFollowers: current?.spotifyFollowers,
    spotifyTopTrack: current?.spotifyTopTrack ?? "",
    appleMonthlyListeners: current?.appleMonthlyListeners,
    appleTopTrack: current?.appleTopTrack ?? "",
    youtubeSubscribers: current?.youtubeSubscribers,
    youtubeTopVideo: current?.youtubeTopVideo ?? "",
    soundcloudFollowers: current?.soundcloudFollowers,
    notes: current?.notes ?? "",
  }));

  function save() {
    setAll((prev) => {
      const idx = prev.findIndex((s) => s.artistSlug === artistSlug);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = draft;
        return copy;
      }
      return [...prev, draft];
    });
    toast({ title: "Snapshot saved", variant: "success" });
  }

  function updateNum(key: keyof StreamingSnapshot, raw: string) {
    const n = raw ? parseInt(raw, 10) : undefined;
    setDraft((d) => ({ ...d, [key]: Number.isFinite(n) ? n : undefined }));
  }

  return (
    <div className="space-y-4">
      <Card>
        <CardContent className="p-5 space-y-3">
          <div className="flex items-center justify-between flex-wrap gap-2 mb-1">
            <div>
              <h3 className="text-sm font-semibold">Streaming snapshot</h3>
              <p className="text-[11px] text-muted-foreground">
                Manual entry today — paste from Spotify-for-Artists, Apple Music for Artists,
                YouTube Studio, SoundCloud Pro. Auto-pull goes live once each API is connected.
              </p>
            </div>
            <Input
              type="date"
              value={draft.asOf}
              onChange={(e) => setDraft({ ...draft, asOf: e.target.value })}
              className="w-44"
            />
          </div>

          <div className="grid gap-3 md:grid-cols-2">
            <PlatformGroup
              icon="🎧"
              label="Spotify"
              color="#1db954"
              fields={[
                {
                  label: "Monthly listeners",
                  value: draft.spotifyMonthlyListeners,
                  onChange: (v) => updateNum("spotifyMonthlyListeners", v),
                },
                {
                  label: "Followers",
                  value: draft.spotifyFollowers,
                  onChange: (v) => updateNum("spotifyFollowers", v),
                },
              ]}
              topTrack={{
                label: "Top track",
                value: draft.spotifyTopTrack,
                onChange: (v) => setDraft({ ...draft, spotifyTopTrack: v }),
              }}
            />
            <PlatformGroup
              icon="🍎"
              label="Apple Music"
              color="#fc3c44"
              fields={[
                {
                  label: "Monthly listeners",
                  value: draft.appleMonthlyListeners,
                  onChange: (v) => updateNum("appleMonthlyListeners", v),
                },
              ]}
              topTrack={{
                label: "Top track",
                value: draft.appleTopTrack,
                onChange: (v) => setDraft({ ...draft, appleTopTrack: v }),
              }}
            />
            <PlatformGroup
              icon="📺"
              label="YouTube"
              color="#ff0000"
              fields={[
                {
                  label: "Subscribers",
                  value: draft.youtubeSubscribers,
                  onChange: (v) => updateNum("youtubeSubscribers", v),
                },
              ]}
              topTrack={{
                label: "Top video",
                value: draft.youtubeTopVideo,
                onChange: (v) => setDraft({ ...draft, youtubeTopVideo: v }),
              }}
            />
            <PlatformGroup
              icon="☁️"
              label="SoundCloud"
              color="#ff5500"
              fields={[
                {
                  label: "Followers",
                  value: draft.soundcloudFollowers,
                  onChange: (v) => updateNum("soundcloudFollowers", v),
                },
              ]}
            />
          </div>

          <Field label="Notes (context for this snapshot)">
            <textarea
              value={draft.notes ?? ""}
              onChange={(e) => setDraft({ ...draft, notes: e.target.value })}
              rows={2}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
              placeholder="e.g. ‘Spike from Trap Sours x Ricoveli collab drop’"
            />
          </Field>

          <div className="flex items-center justify-end gap-2">
            <Button variant="brand" size="sm" onClick={save}>
              Save snapshot
            </Button>
          </div>
        </CardContent>
      </Card>

      {current && (
        <Card className="border-dashed">
          <CardContent className="p-5 text-xs text-muted-foreground">
            Last snapshot saved {formatDate(current.asOf)}. When real API integrations land
            (Spotify-for-Artists, Apple Music for Artists), this view auto-refreshes daily.
            Historical snapshots will let us chart growth over time.
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function PlatformGroup({
  icon,
  label,
  color,
  fields,
  topTrack,
}: {
  icon: string;
  label: string;
  color: string;
  fields: Array<{ label: string; value: number | undefined; onChange: (v: string) => void }>;
  topTrack?: { label: string; value: string | undefined; onChange: (v: string) => void };
}) {
  return (
    <Card>
      <CardContent className="p-4">
        <div className="flex items-center gap-2 mb-3">
          <span
            className="w-8 h-8 rounded-full flex items-center justify-center text-base"
            style={{ backgroundColor: `${color}25` }}
          >
            {icon}
          </span>
          <h4 className="text-sm font-semibold">{label}</h4>
        </div>
        <div className="space-y-2">
          {fields.map((f) => (
            <Field key={f.label} label={f.label}>
              <Input
                type="number"
                value={f.value ?? ""}
                onChange={(e) => f.onChange(e.target.value)}
                placeholder="0"
              />
            </Field>
          ))}
          {topTrack && (
            <Field label={topTrack.label}>
              <Input
                value={topTrack.value ?? ""}
                onChange={(e) => topTrack.onChange(e.target.value)}
                placeholder="Track title"
              />
            </Field>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Shared
// ──────────────────────────────────────────────────────────────────────────

function Field({
  label,
  children,
  className,
}: {
  label: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <div className={className}>
      <label className="text-xs text-muted-foreground">{label}</label>
      <div className="mt-1">{children}</div>
    </div>
  );
}
