// SONARA — Feed (shared across artista/producer/manager)
// Instagram-light per il marketplace: scoperta, niente vanity, niente comments.
// Engagement → DM. Like/Save sono privati.

const FeedIcons = window.SonaraIcons;

/* ─────────── Algo explanation tooltips ─────────── */
const FEED_ALGO = {
  perte: "Match coi tuoi generi · boost geografico 25% · attività recente 15%",
  vicini: "Solo post da tua città/regione · cronologico",
  recenti: "Cronologico puro · nessun algoritmo",
};

/* ─────────── Mock data ─────────── */
const FEED_POSTS = [
  {
    id: "f1", type: "beat", time: "12m fa",
    author: { name: "Nico Vega", handle: "@nicovega", init: "NV", role: "Producer", verified: true, city: "Milano" },
    content: {
      title: "Notturno", subtitle: "Trap dark · 142 BPM · F# min",
      cover: "g1", price: 45, exclusive: 350, duration: "3:12",
      tags: ["Trap", "Dark", "808 pesanti"],
    },
  },
  {
    id: "f2", type: "open_call", time: "32m fa",
    author: { name: "Alessio Marchetti", handle: "@alessiorap", init: "AR", role: "Artista", verified: true, city: "Milano" },
    content: {
      kind: "Cerco beat custom",
      brief: "Cerco beat trap 808 pesante stile Travis Scott late-night. Per uscita estate, EP 5 tracce. Ref: After Hours, Headlines.",
      budget: { min: 100, max: 200 }, deadline: "10gg", offers: 4,
      tags: ["Trap", "Custom", "BPM 138-145"],
    },
  },
  {
    id: "f3", type: "status", time: "1h fa",
    author: { name: "Studio Riva", handle: "@studioriva", init: "SR", role: "Producer", verified: true, city: "Bologna", studio: true },
    content: {
      text: "Aperto a 2 mix questa settimana — preferenza cantautorato / indie. Risposte entro 6h, niente listing pubblico per ora. Scrivetemi in DM con stems già pronti.",
    },
  },
  {
    id: "f4", type: "servizio", time: "2h fa",
    author: { name: "Sara D'Onofrio", handle: "@saradonofrio", init: "SD", role: "Producer", verified: true, city: "Milano" },
    content: {
      title: "Vocal production + tuning premium",
      category: "Vocal production",
      from: 120, delivery: "2gg", revisions: 2,
      tags: ["R&B", "Alt-pop", "Indie"],
      teaser: "Lavoro con voci femminili emergenti, già 52 progetti chiusi su Sonara.",
    },
  },
  {
    id: "f5", type: "open_call", time: "3h fa",
    author: { name: "Andrea Conti", handle: "@andreaconti", init: "AC", role: "Manager", verified: true, city: "Milano" },
    content: {
      kind: "Cerco talenti per roster",
      brief: "Sto aprendo 1-2 posizioni nel roster per artisti alt-pop / indie tra i 18 e i 26 anni con almeno un singolo pubblicato. Focus campagna 2027.",
      tags: ["Alt-pop", "Indie", "Cantautorato"],
    },
  },
  {
    id: "f6", type: "beat", time: "5h fa",
    author: { name: "Yoshi K.", handle: "@yoshik", init: "YK", role: "Producer", verified: false, city: "Milano" },
    content: {
      title: "Lupo Solitario", subtitle: "Drill UK · 145 BPM · D min",
      cover: "g3", price: 40, exclusive: 300, duration: "2:55",
      tags: ["Drill", "UK", "Dark"],
    },
  },
  {
    id: "f7", type: "milestone", time: "Ieri",
    author: { name: "Marco Vitale", handle: "@marcovit", init: "MV", role: "Producer", verified: true, city: "Roma" },
    content: {
      icon: "trophy",
      text: "Ho appena chiuso il 50° ordine su Sonara. Grazie a tutti gli artisti R&B che mi hanno scelto in questi 2 anni 🎚",
      stat: "50 ordini chiusi · ★ 4.9 media",
    },
  },
  {
    id: "f8", type: "status", time: "Ieri",
    author: { name: "Giulia Wave", handle: "@giuliawave", init: "GW", role: "Artista", verified: false, city: "Milano" },
    content: {
      text: "Primo singolo \"Marble\" è fuori su tutte le piattaforme. Grazie a chi ha mixato e masterizzato con me su Sonara. Disponibile per featuring alt-pop.",
    },
  },
  {
    id: "f9", type: "servizio", time: "2gg fa",
    author: { name: "Diego K.", handle: "@diegok", init: "DK", role: "Producer", verified: true, city: "Napoli" },
    content: {
      title: "Custom production afro/trap",
      category: "Custom production",
      from: 90, delivery: "5gg", revisions: 3,
      tags: ["Afro", "Trap", "Hip-hop"],
      teaser: "Beat su brief con stems separati e mix base inclusi.",
    },
  },
];

/* ─────────── Composer (sticky) ─────────── */
function FeedComposer({ role }) {
  const [open, setOpen] = React.useState(false);
  const [type, setType] = React.useState(null);
  const [text, setText] = React.useState("");

  const types = [
    role === "manager" ?
      { v: "open_call", l: "Open call talenti", s: "Cerco artisti per il mio roster", ic: "users" } :
    role === "artista" ?
      { v: "open_call", l: "Pubblica richiesta", s: "Cerco un beat / mix / servizio", ic: "target" } :
      { v: "beat", l: "Annuncia un nuovo beat", s: "Riprendi dal catalog", ic: "disc" },
    role === "producer" ?
      { v: "servizio", l: "Annuncia un servizio", s: "Mix / master / custom / vocal", ic: "mixer" } :
      { v: "open_call", l: "Open call featuring", s: "Cerco collab", ic: "collaboration" },
    { v: "status", l: "Status / disponibilità", s: "Aggiornamento veloce (max 280)", ic: "zap" },
  ].filter(Boolean);

  return (
    <>
      <button className="feed-composer-pill" onClick={() => setOpen(true)}>
        <span className="feed-composer-av">{role === "manager" ? "AC" : role === "artista" ? "LM" : "NV"}</span>
        <span className="feed-composer-prompt">
          {role === "manager" ? "Cerca talenti o condividi un aggiornamento…"
            : role === "artista" ? "Cerca un beat, condividi un'uscita…"
            : "Annuncia un beat, un servizio o la tua disponibilità…"}
        </span>
        <span className="feed-composer-btn"><FeedIcons.edit size={13}/> Nuovo post</span>
      </button>

      {open && (
        <div className="feed-modal-backdrop" onClick={() => setOpen(false)}>
          <div className="feed-modal" onClick={(e) => e.stopPropagation()}>
            <header className="feed-modal-head">
              <div className="feed-modal-title">{type ? types.find(t => t.v === type)?.l : "Cosa vuoi condividere?"}</div>
              <button className="feed-modal-close" onClick={() => setOpen(false)}><FeedIcons.close size={14}/></button>
            </header>

            {!type && (
              <div className="feed-type-list">
                {types.map(t => {
                  const Ic = FeedIcons[t.ic] || FeedIcons.zap;
                  return (
                    <button key={t.v} className="feed-type-opt" onClick={() => setType(t.v)}>
                      <span className="feed-type-ic"><Ic size={16}/></span>
                      <div className="feed-type-meta">
                        <div className="t">{t.l}</div>
                        <div className="s">{t.s}</div>
                      </div>
                      <FeedIcons.arrowRight size={13}/>
                    </button>
                  );
                })}
              </div>
            )}

            {type === "status" && (
              <div className="feed-compose-form">
                <textarea
                  className="feed-textarea"
                  rows={5}
                  placeholder="Cosa vuoi condividere? Disponibilità, news, prossimi progetti…"
                  maxLength={280}
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                  autoFocus
                />
                <div className="feed-compose-foot">
                  <span className="feed-counter">{text.length}/280</span>
                  <button className="feed-publish" disabled={text.length < 5} onClick={() => setOpen(false)}>
                    Pubblica <FeedIcons.arrowRight size={12}/>
                  </button>
                </div>
              </div>
            )}

            {(type === "beat" || type === "servizio") && (
              <div className="feed-compose-form">
                <div className="feed-pick-from-catalog">
                  <FeedIcons.disc size={14}/>
                  Scegli {type === "beat" ? "un beat" : "un servizio"} dal tuo catalog →
                </div>
                <div className="feed-catalog-list">
                  {[1,2,3].map(i => (
                    <button key={i} className="feed-catalog-item">
                      <span className={`feed-cat-cover g${i}`}/>
                      <div className="feed-cat-meta">
                        <div className="t">{type === "beat" ? ["Notturno","Asfalto","Lupo"][i-1] : ["Mix stereo","Custom prod","Vocal prod"][i-1]}</div>
                        <div className="s">{type === "beat" ? ["142 BPM · F# min · €45","138 BPM · G min · €50","145 BPM · D min · €40"][i-1] : ["da €80 · 3gg · 24 ordini","da €350 · 7gg · 8 ordini","da €90 · 2gg · 15 ordini"][i-1]}</div>
                      </div>
                    </button>
                  ))}
                </div>
                <textarea
                  className="feed-textarea"
                  rows={2}
                  placeholder="Aggiungi un commento (opzionale, max 200)…"
                  maxLength={200}
                />
                <div className="feed-compose-foot">
                  <span className="feed-counter">3 post oggi / 3 max</span>
                  <button className="feed-publish" onClick={() => setOpen(false)}>
                    Pubblica <FeedIcons.arrowRight size={12}/>
                  </button>
                </div>
              </div>
            )}

            {type === "open_call" && (
              <div className="feed-compose-form">
                <input className="feed-input" placeholder={role === "manager" ? "Cerco artisti…" : role === "artista" ? "Cerco un beat / mix / …" : "Cerco collab / featuring…"}/>
                <textarea
                  className="feed-textarea"
                  rows={4}
                  placeholder="Descrivi cosa cerchi. Generi, riferimenti, budget, deadline…"
                  maxLength={500}
                />
                <div className="feed-compose-foot">
                  <span className="feed-counter">Visibile a tutti i ruoli per 14 giorni</span>
                  <button className="feed-publish" onClick={() => setOpen(false)}>
                    Pubblica <FeedIcons.arrowRight size={12}/>
                  </button>
                </div>
              </div>
            )}

            {type && (
              <button className="feed-modal-back" onClick={() => setType(null)}>← Cambia tipo</button>
            )}
          </div>
        </div>
      )}
    </>
  );
}

/* ─────────── Author header (riusato in tutte le card) ─────────── */
function FeedAuthor({ author, time, role: viewerRole }) {
  return (
    <header className="feed-author">
      <span className={`feed-av art-${author.init.charCodeAt(0) % 6}`}>{author.init}</span>
      <div className="feed-author-meta">
        <div className="row1">
          <span className="nm">{author.name}</span>
          {author.verified && <span className="ver"><FeedIcons.verified size={11}/></span>}
          <span className={`role-tag ${author.role.toLowerCase()}`}>{author.role}</span>
          {author.studio && <span className="role-tag studio">Studio</span>}
        </div>
        <div className="row2">
          <span>{author.handle}</span>
          <span className="sep">·</span>
          <span>{author.city}</span>
          <span className="sep">·</span>
          <span className="t">{time}</span>
        </div>
      </div>
      <button className="feed-more"><FeedIcons.more size={14}/></button>
    </header>
  );
}

/* ─────────── Engagement footer (private heart + save + open + DM) ─────────── */
function FeedEngagement({ post, liked, saved, onLike, onSave, openLabel, onOpen }) {
  return (
    <footer className="feed-actions">
      <button className={`feed-act ${liked ? "active heart" : ""}`} onClick={onLike} title="Salva privatamente (non visibile ad altri)">
        <svg width="15" height="15" viewBox="0 0 24 24" fill={liked ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
        <span>Mi piace</span>
      </button>
      <button className={`feed-act ${saved ? "active bookmark" : ""}`} onClick={onSave} title="Aggiungi a Preferiti">
        <svg width="14" height="14" viewBox="0 0 24 24" fill={saved ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
        <span>Salva</span>
      </button>
      <button className="feed-act" onClick={onOpen}>
        <FeedIcons.arrowRight size={14}/>
        <span>{openLabel}</span>
      </button>
      <span className="feed-act-spacer"/>
      <button className="feed-act dm" title="Manda DM all'autore">
        <FeedIcons.message size={14}/>
        <span>DM</span>
      </button>
    </footer>
  );
}

/* ─────────── Tipo specific bodies ─────────── */

function BeatBody({ c }) {
  return (
    <div className="feed-beat-card">
      <div className={`feed-beat-cover ${c.cover}`}>
        <button className="feed-beat-play"><FeedIcons.play size={14}/></button>
        <div className="feed-wave">
          {Array.from({ length: 48 }).map((_, i) => (
            <span key={i} style={{
              height: `${20 + ((Math.sin(i * 0.5) + 1) * 30 + (i % 7) * 4)}%`,
              animationDelay: `${i * 30}ms`,
            }}/>
          ))}
        </div>
      </div>
      <div className="feed-beat-body">
        <div className="feed-beat-h">
          <div className="feed-beat-title">{c.title}</div>
          <div className="feed-beat-price">€{c.price}<span className="excl">/ €{c.exclusive} excl.</span></div>
        </div>
        <div className="feed-beat-sub">{c.subtitle} · {c.duration}</div>
        <div className="feed-tag-row">
          {c.tags.map(t => <span key={t} className="feed-tag">{t}</span>)}
        </div>
      </div>
    </div>
  );
}

function ServizioBody({ c }) {
  return (
    <div className="feed-serv-card">
      <div className="feed-serv-cat">{c.category}</div>
      <div className="feed-serv-title">{c.title}</div>
      <p className="feed-serv-teaser">{c.teaser}</p>
      <div className="feed-serv-meta">
        <span><strong>da €{c.from}</strong></span>
        <span className="sep">·</span>
        <span>Consegna {c.delivery}</span>
        <span className="sep">·</span>
        <span>{c.revisions} revisioni</span>
      </div>
      <div className="feed-tag-row">
        {c.tags.map(t => <span key={t} className="feed-tag">{t}</span>)}
      </div>
    </div>
  );
}

function OpenCallBody({ c }) {
  return (
    <div className="feed-call-card">
      <div className="feed-call-eyebrow">
        <FeedIcons.target size={11}/> {c.kind}
      </div>
      <p className="feed-call-brief">{c.brief}</p>
      <div className="feed-call-meta">
        {c.budget && <span><strong>€{c.budget.min}–€{c.budget.max}</strong></span>}
        {c.deadline && <><span className="sep">·</span><span>Consegna {c.deadline}</span></>}
        {c.offers != null && <><span className="sep">·</span><span>{c.offers} offerte</span></>}
      </div>
      {c.tags && (
        <div className="feed-tag-row">
          {c.tags.map(t => <span key={t} className="feed-tag">{t}</span>)}
        </div>
      )}
    </div>
  );
}

function StatusBody({ c }) {
  return <p className="feed-status-text">{c.text}</p>;
}

function MilestoneBody({ c }) {
  return (
    <div className="feed-milestone">
      <div className="feed-milestone-ic">🏆</div>
      <div className="feed-milestone-body">
        <p>{c.text}</p>
        <div className="feed-milestone-stat">{c.stat}</div>
      </div>
    </div>
  );
}

/* ─────────── Card wrapper ─────────── */
function FeedCard({ post }) {
  const [liked, setLiked] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  const openLabel = {
    beat: "Vai al beat", servizio: "Vai al servizio", open_call: "Apri richiesta",
    status: "Profilo", milestone: "Profilo",
  }[post.type];

  return (
    <article className={`feed-card feed-card-${post.type}`}>
      <FeedAuthor author={post.author} time={post.time}/>
      <div className="feed-body">
        {post.type === "beat" && <BeatBody c={post.content}/>}
        {post.type === "servizio" && <ServizioBody c={post.content}/>}
        {post.type === "open_call" && <OpenCallBody c={post.content}/>}
        {post.type === "status" && <StatusBody c={post.content}/>}
        {post.type === "milestone" && <MilestoneBody c={post.content}/>}
      </div>
      <FeedEngagement
        post={post}
        liked={liked} saved={saved}
        onLike={() => setLiked(!liked)}
        onSave={() => setSaved(!saved)}
        openLabel={openLabel}
        onOpen={() => {}}
      />
    </article>
  );
}

/* ─────────── Feed page ─────────── */
function FeedPage({ role = "producer" }) {
  const [tab, setTab] = React.useState("perte");
  const [filter, setFilter] = React.useState("all"); // all | beat | servizio | open_call | status

  const filtered = FEED_POSTS.filter(p => filter === "all" || p.type === filter);

  return (
    <main className="page feed-page" data-screen-label="Feed">
      <div className="feed-header">
        <div>
          <h1 className="feed-h1">Feed</h1>
          <div className="feed-sub">Le ultime sulla piattaforma · {FEED_POSTS.length} nuovi post oggi</div>
        </div>
      </div>

      <div className="feed-tabs">
        <button className={`feed-tab ${tab === "perte" ? "active" : ""}`} onClick={() => setTab("perte")}>
          <FeedIcons.zap size={12}/> Per te
        </button>
        <button className={`feed-tab ${tab === "vicini" ? "active" : ""}`} onClick={() => setTab("vicini")}>
          <FeedIcons.pin size={12}/> Vicini
        </button>
        <button className={`feed-tab ${tab === "recenti" ? "active" : ""}`} onClick={() => setTab("recenti")}>
          <FeedIcons.clock size={12}/> Recenti
        </button>
        <span className="feed-algo" title={FEED_ALGO[tab]}>
          <FeedIcons.info size={12}/>
        </span>
      </div>

      <FeedComposer role={role}/>

      <div className="feed-filter-chips">
        {[
          ["all", "Tutto"],
          ["beat", "Beat"],
          ["servizio", "Servizi"],
          ["open_call", "Open call"],
          ["status", "News"],
        ].map(([v, l]) => (
          <button key={v} className={`feed-chip ${filter === v ? "active" : ""}`} onClick={() => setFilter(v)}>
            {l}
          </button>
        ))}
      </div>

      <div className="feed-stream">
        {filtered.map(p => <FeedCard key={p.id} post={p}/>)}
        <div className="feed-end">
          <FeedIcons.check size={16}/>
          Sei in pari.
        </div>
      </div>
    </main>
  );
}

window.FeedPage = FeedPage;
