// use-user-data.jsx — useUserData hook: all data state, auth, and Firestore handlers.
// Depends on: firestore-service.js (db, auth, firestoreXxx functions) and mmv-data.js (COLLABS, ARTISTS, PUBLISHERS, CONTACTS).

const { useState, useEffect } = React;

const SEED_CAMPAIGNS = [
  {
    id: "cameron-library",
    name: "Cameron Taylor Library",
    pitchTemplate: {
      subject: "Dark Pop & Cinematic Sync Catalog — Cameron Taylor Music",
      body: `Hi {{contactName}},

I'm Cameron Taylor — a music producer and composer based in Australia, specialising in dark pop and cinematic music for TV, film, and streaming.

I'm reaching out to introduce my sync catalog and see if there's a fit for your slate.

What I have:
- 50 tracks across dark pop and cinematic — instrumentals and acapellas available for all
- Fully cleared and metadata-tagged, ready to license
- Custom brief capacity — I work with a vetted network of professional songwriters and vocalists and can turn around bespoke tracks quickly

Listen here: https://s.disco.ac/cycjmpwiovta

{{customNote}}

I'm open to exclusive and non-exclusive arrangements depending on the opportunity, and happy to discuss placement fees, backend splits, or brief-based work.

If the sound fits anything you're currently working on, I'd love to hear from you.

Cameron Taylor
Cameron Taylor Music
info@camerontaylormusic.com.au`
    },
    followUpTemplate: {
      subject: "Re: Dark Pop & Cinematic Sync Catalog — Cameron Taylor Music",
      body: `Hi {{contactName}},

Circling back on this — happy to curate a selection if it's easier.

Cameron`
    },
    createdAt: Date.now()
  },
  {
    id: "kyte-publishing",
    name: "KYTE Publishing",
    pitchTemplate: {
      subject: "Korean Music Catalog for Sync — KYTE Publishing (AU Representative)",
      body: `Hi {{contactName}},

I'm Cameron Taylor, Australian sub-publisher for KYTE — a South Korean publisher with a catalog of 100+ tracks across indie Korean rock, K-pop, and lo-fi hip hop.

With Korean content continuing to dominate Netflix and streaming globally, KYTE's catalog is well-positioned for projects that need authentic Korean sounds — from drama underscores to contemporary commercial placements.

What's available:
- 100+ cleared tracks across K-pop, indie Korean rock, and lo-fi hip hop
- Stems and alternatives available on request
- KYTE's producers are available for custom briefs

I'm authorised to pitch, negotiate, and broker sync deals internationally on KYTE's behalf.

{{customNote}}

Happy to send a curated selection based on your current needs — just let me know the vibe or brief.

Cameron Taylor
Cameron Taylor Music (AU Sub-Publisher, KYTE)
info@camerontaylormusic.com.au`
    },
    followUpTemplate: {
      subject: "Re: Korean Music Catalog for Sync — KYTE Publishing",
      body: `Hi {{contactName}},

Circling back — happy to put together a curated selection if that's easier.

Cameron`
    },
    createdAt: Date.now()
  }
];

function useUserData() {
  const [user,               setUser]               = useState(null);
  const [authReady,          setAuthReady]          = useState(false);
  const [subscriptionStatus, setSubscriptionStatus] = useState('loading');
  const [profile,            setProfile]            = useState({});
  const [songs,              setSongs]              = useState([]);
  const [contacts,   setContacts]   = useState([]);
  const [briefs,     setBriefs]     = useState([]);
  const [collabs,    setCollabs]    = useState(COLLABS);
  const [artists,    setArtists]    = useState(ARTISTS);
  const [publishers, setPublishers] = useState(PUBLISHERS);
  const [campaigns,    setCampaigns]    = useState([]);
  const [pitchEntries, setPitchEntries] = useState([]);

  // Auth state listener — drives all data loading
  useEffect(() => {
    return auth.onAuthStateChanged(async (u) => {
      setUser(u);
      if (u) {
        const token = await u.getIdTokenResult();
        if (token.claims.admin) {
          setSubscriptionStatus('bypass');
        } else {
          db.collection('customers').doc(u.uid).collection('subscriptions')
            .where('status', 'in', ['trialing', 'active'])
            .onSnapshot(
              snap => setSubscriptionStatus(snap.empty ? 'none' : snap.docs[0].data().status),
              ()   => setSubscriptionStatus('none')
            );
        }

        const alreadySeeded = await firestoreCheckSeeded(u.uid);
        if (!alreadySeeded) {
          await Promise.all([
            firestoreSeedCollectionIfEmpty(u.uid, "collabs", COLLABS),
            firestoreSeedCollectionIfEmpty(u.uid, "artists", ARTISTS),
            firestoreSeedCollectionIfEmpty(u.uid, "publishers", PUBLISHERS),
          ]);
          await firestoreMarkSeeded(u.uid);
        }
        const [data, loadedCampaigns, prof] = await Promise.all([
          firestoreLoadUserData(u.uid),
          firestoreLoadCampaigns(u.uid),
          firestoreLoadProfile(u.uid),
        ]);
        setProfile(prof);
        setSongs(data.songs);
        setContacts(data.contacts.length ? data.contacts : CONTACTS);
        setBriefs(data.briefs);
        setCollabs(data.collabs.length ? data.collabs : COLLABS);
        setArtists(data.artists.length ? data.artists : ARTISTS);
        setPublishers(data.publishers.length ? data.publishers : PUBLISHERS);

        let finalCampaigns = loadedCampaigns;
        if (!loadedCampaigns.length) {
          const seededCampaigns = SEED_CAMPAIGNS.map(c => ({ ...c, createdAt: Date.now() }));
          await Promise.all(seededCampaigns.map(c => firestoreAddCampaign(u.uid, c)));
          finalCampaigns = seededCampaigns;
        }
        setCampaigns(finalCampaigns);

        const allEntries = await Promise.all(
          finalCampaigns.map(c =>
            firestoreLoadPitchEntries(u.uid, c.id)
              .then(entries => entries.map(e => ({ ...e, campaignId: c.id })))
          )
        );
        setPitchEntries(allEntries.flat());
      } else {
        setProfile({});
        setSongs([]);
        setContacts([]);
        setBriefs([]);
        setCollabs(COLLABS);
        setArtists(ARTISTS);
        setPublishers(PUBLISHERS);
        setCampaigns([]);
        setPitchEntries([]);
        setSubscriptionStatus('loading');
      }
      setAuthReady(true);
    });
  }, []);

  // ─── Song handlers ───────────────────────────────────────────────────────────

  const handleUpdateSong = (id, updates) => {
    setSongs(prev => prev.map(s => s.id === id ? {...s, ...updates} : s));
    if (user) firestoreUpdateSong(user.uid, id, updates).catch(console.error);
  };

  const handleDeleteSong = (id) => {
    setSongs(prev => prev.filter(s => s.id !== id));
    if (user) firestoreDeleteSong(user.uid, id).catch(console.error);
  };

  const handleAddSong = async (s) => {
    let newSong = { ...s, createdAt: Date.now(), lyrics: "", splitSheetUrl: "", embedCode: "", pubRegistered: false, agencyIds: [] };
    if (user) {
      newSong = await firestoreAddSong(user.uid, newSong);
    }
    setSongs(prev => [newSong, ...prev]);
  };

  const handleSaveSplits = (songId, newSplits) => {
    handleUpdateSong(songId, { splits: newSplits, splitConflict: false });
  };

  // ─── Contact handlers ────────────────────────────────────────────────────────

  const handleUpdateContact = (id, updates) => {
    setContacts(prev => prev.map(c => c.id === id ? {...c, ...updates} : c));
    if (user) firestoreUpdateContact(user.uid, id, updates).catch(console.error);
  };

  // ─── Collab handlers ─────────────────────────────────────────────────────────

  const handleAddCollab = (newCollab) => {
    COLLABS.push(newCollab); // kept: KYTE export reads global COLLABS directly
    setCollabs(prev => [...prev, newCollab]);
    if (user) firestoreWriteCollab(user.uid, newCollab).catch(console.error);
  };

  const handleUpdateCollab = (id, updates) => {
    if ('publisherId' in updates) {
      const oldCollab = collabs.find(c => c.id === id);
      const oldPubId  = oldCollab?.publisherId;
      const newPubId  = updates.publisherId;
      if (oldPubId !== newPubId) {
        if (oldPubId) {
          const oldPub = publishers.find(p => p.id === oldPubId);
          if (oldPub) {
            const roster = (oldPub.roster||[]).filter(rid => rid !== id);
            setPublishers(prev => prev.map(p => p.id === oldPubId ? {...p, roster} : p));
            if (user) firestoreUpdatePublisher(user.uid, oldPubId, { roster }).catch(console.error);
          }
        }
        if (newPubId) {
          const newPub = publishers.find(p => p.id === newPubId);
          if (newPub) {
            const roster = [...new Set([...(newPub.roster||[]), id])];
            setPublishers(prev => prev.map(p => p.id === newPubId ? {...p, roster} : p));
            if (user) firestoreUpdatePublisher(user.uid, newPubId, { roster }).catch(console.error);
          }
        }
      }
    }
    setCollabs(prev => prev.map(c => c.id === id ? {...c, ...updates} : c));
    if (user) firestoreUpdateCollab(user.uid, id, updates).catch(console.error);
  };

  const handleDeleteCollab = (id) => {
    setCollabs(prev => prev.filter(c => c.id !== id));
    if (user) firestoreDeleteCollab(user.uid, id).catch(console.error);
  };

  // ─── Artist handlers ─────────────────────────────────────────────────────────

  const handleAddArtist = (newArtist) => {
    ARTISTS.push(newArtist); // kept: consistent with handleAddCollab global mutation
    setArtists(prev => [...prev, newArtist]);
    if (user) firestoreWriteArtist(user.uid, newArtist).catch(console.error);
  };

  const handleUpdateArtist = (id, updates) => {
    setArtists(prev => prev.map(a => a.id === id ? {...a, ...updates} : a));
    if (user) firestoreUpdateArtist(user.uid, id, updates).catch(console.error);
  };

  const handleDeleteArtist = (id) => {
    setArtists(prev => prev.filter(a => a.id !== id));
    if (user) firestoreDeleteArtist(user.uid, id).catch(console.error);
  };

  // ─── Publisher handlers ──────────────────────────────────────────────────────

  const handleAddPublisher = (newPublisher) => {
    setPublishers(prev => [...prev, newPublisher]);
    if (user) firestoreWritePublisher(user.uid, newPublisher).catch(console.error);
    // Auto-create a linked contact entry
    const newContact = {
      id:          String(newPublisher.id) + "_pub",
      name:        newPublisher.name,
      type:        "Publisher",
      email:       newPublisher.email || "",
      website:     newPublisher.website || "",
      notes:       newPublisher.notes || "",
      publisherId: newPublisher.id,
    };
    setContacts(prev => [...prev, newContact]);
    if (user) firestoreWriteContact(user.uid, newContact).catch(console.error);
    return newPublisher;
  };

  const handleUpdatePublisher = (id, updates) => {
    setPublishers(prev => prev.map(p => p.id === id ? {...p, ...updates} : p));
    if (user) firestoreUpdatePublisher(user.uid, id, updates).catch(console.error);
  };

  const handleDeletePublisher = (id) => {
    setPublishers(prev => prev.filter(p => p.id !== id));
    if (user) firestoreDeletePublisher(user.uid, id).catch(console.error);
  };

  // ─── Brief handlers ──────────────────────────────────────────────────────────

  const handleAddBrief = async (brief) => {
    const id = String(Date.now());
    const newBrief = { ...brief, id, createdAt: Date.now(), submittedSongs: brief.submittedSongs||[], mood: brief.mood||[], genre: brief.genre||[], source: brief.source||"manual" };
    setBriefs(prev => [newBrief, ...prev]);
    if (user) firestoreAddBrief(user.uid, newBrief).catch(console.error);
    return newBrief;
  };

  const handleUpdateBrief = (id, updates) => {
    setBriefs(prev => prev.map(b => b.id === id ? {...b, ...updates} : b));
    if (user) firestoreUpdateBrief(user.uid, id, updates).catch(console.error);
  };

  const handleDeleteBrief = (id) => {
    setBriefs(prev => prev.filter(b => b.id !== id));
    if (user) firestoreDeleteBrief(user.uid, id).catch(console.error);
  };

  // ─── Campaign handlers ───────────────────────────────────────────────────────

  const handleAddCampaign = (campaign) => {
    const newCampaign = { ...campaign, id: campaign.id || String(Date.now()), createdAt: campaign.createdAt || Date.now() };
    setCampaigns(prev => [...prev, newCampaign]);
    if (user) firestoreAddCampaign(user.uid, newCampaign).catch(console.error);
    return newCampaign;
  };

  const handleUpdateCampaign = (id, updates) => {
    setCampaigns(prev => prev.map(c => c.id === id ? { ...c, ...updates } : c));
    if (user) firestoreUpdateCampaign(user.uid, id, updates).catch(console.error);
  };

  const handleDeleteCampaign = (id) => {
    setCampaigns(prev => prev.filter(c => c.id !== id));
    setPitchEntries(prev => prev.filter(e => e.campaignId !== id));
    if (user) firestoreDeleteCampaign(user.uid, id).catch(console.error);
  };

  // ─── Pitch entry handlers ─────────────────────────────────────────────────────

  const handleAddPitchEntry = (campaignId, entry) => {
    const newEntry = { ...entry, id: entry.id || String(Date.now()), campaignId, createdAt: entry.createdAt || Date.now(), updatedAt: Date.now() };
    setPitchEntries(prev => [...prev, newEntry]);
    if (user) firestoreAddPitchEntry(user.uid, campaignId, newEntry).catch(console.error);
    return newEntry;
  };

  const handleUpdatePitchEntry = (campaignId, id, updates) => {
    setPitchEntries(prev => prev.map(e => e.id === id && e.campaignId === campaignId ? { ...e, ...updates, updatedAt: Date.now() } : e));
    if (user) firestoreUpdatePitchEntry(user.uid, campaignId, id, { ...updates, updatedAt: Date.now() }).catch(console.error);
  };

  const handleDeletePitchEntry = (campaignId, id) => {
    setPitchEntries(prev => prev.filter(e => !(e.id === id && e.campaignId === campaignId)));
    if (user) firestoreDeletePitchEntry(user.uid, campaignId, id).catch(console.error);
  };

  // ─── Bulk import ─────────────────────────────────────────────────────────────

  const handleSetSongs = async (updaterOrArray) => {
    const newSongs = typeof updaterOrArray === "function" ? updaterOrArray(songs) : updaterOrArray;
    setSongs(newSongs);
    if (user) firestoreSyncAllSongs(user.uid, newSongs).catch(console.error);
  };

  // ─── Profile handlers ────────────────────────────────────────────────────────

  const handleUpdateProfile = (updates) => {
    setProfile(prev => ({ ...prev, ...updates }));
    if (user) firestoreUpdateProfile(user.uid, updates).catch(console.error);
  };

  const handleLogout = () => auth.signOut();

  const handleDeleteAllData = async () => {
    if (!user) return;
    await firestoreDeleteAllUserData(user.uid);
    window.location.reload();
  };

  return {
    user, authReady, subscriptionStatus,
    profile,
    songs, contacts, briefs, collabs, artists, publishers,
    campaigns, pitchEntries,
    handleUpdateProfile,
    handleUpdateSong, handleDeleteSong, handleAddSong, handleSaveSplits,
    handleAddCollab, handleUpdateCollab, handleDeleteCollab,
    handleAddArtist, handleUpdateArtist, handleDeleteArtist,
    handleAddPublisher, handleUpdatePublisher, handleDeletePublisher,
    handleUpdateContact,
    handleAddBrief, handleUpdateBrief, handleDeleteBrief,
    handleAddCampaign, handleUpdateCampaign, handleDeleteCampaign,
    handleAddPitchEntry, handleUpdatePitchEntry, handleDeletePitchEntry,
    handleSetSongs, handleLogout, handleDeleteAllData,
  };
}
