// ─────────────────────────────────────────────────────────
// ChefVerse · Briefs marketplace + detail
// ─────────────────────────────────────────────────────────
const { useState: useStateBr } = React;

const BRIEF_IMAGES = [
  "uploads/brief-1.jpg",
  "uploads/brief-2.jpg",
  "uploads/brief-3.jpg",
  "uploads/brief-4.jpg",
];
function briefImageFor(id) {
  const idx = (id.split("").reduce((a, c) => a + c.charCodeAt(0), 0)) % BRIEF_IMAGES.length;
  return BRIEF_IMAGES[idx];
}

function Briefs({ locale, onOpenBrief, onOpenAbout }) {
  const t = window.I18N[locale];
  const tb = t.briefs;
  const [pillar, setPillar] = useStateBr("all");
  const recap = {
    eyebrow: locale === "de" ? "NEU HIER?" : locale === "id" ? "BARU DI SINI?" : "NEW HERE?",
    title: locale === "de" ? "Wer wir sind & wie Briefings funktionieren" : locale === "id" ? "Siapa kami & cara kerja brief" : "Who we are & how briefs work",
    body: locale === "de" ? "Eine kurze Auffrischung zu UFS und wie du an Briefings herangehst." : locale === "id" ? "Pengingat singkat tentang UFS dan cara menjalankan brief." : "A quick recap on UFS and how to approach briefs.",
    cta: locale === "de" ? "Mehr erfahren" : locale === "id" ? "Pelajari" : "Learn more",
  };
  const list = window.BRIEFS.filter(b => {
    if (pillar !== "all" && b.pillar !== pillar) return false;
    return true;
  });

  const featured = window.BRIEFS.find(b => b.featured) || window.BRIEFS[0];

  return (
    <div className="page page-briefs">
      <div className="page-head">
        <div>
          <h1>{tb.heading}</h1>
          <p className="page-sub">{tb.sub}</p>
        </div>
        <div className="head-actions">
          <button className="btn btn-outline"><Icon name="filter" size={14} /> {t.course.filter}</button>
          <button className="btn btn-outline"><Icon name="bookmark" size={14} /> Saved</button>
        </div>
      </div>

      {/* Who we are / how briefs work — light recap, links to About UFS */}
      <button className="brief-recap" onClick={() => onOpenAbout && onOpenAbout()}>
        <div className="brief-recap-ic"><Icon name="info" size={18} /></div>
        <div className="brief-recap-body">
          <span className="brief-recap-eyebrow">{recap.eyebrow}</span>
          <div className="brief-recap-title">{recap.title}</div>
          <div className="brief-recap-sub">{recap.body}</div>
        </div>
        <span className="brief-recap-cta">{recap.cta} <Icon name="arrow-right" size={13} /></span>
      </button>

      {/* Featured brief band */}
      <div className="brief-featured">
        <div className="brief-featured-cover" style={{ background: `linear-gradient(135deg, ${window.PILLARS[featured.pillar].color}, var(--squid-ink))` }}>
          <img src={briefImageFor(featured.id)} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.7, zIndex: 0 }} />
          <div style={{ position: "absolute", inset: 0, zIndex: 1, background: "linear-gradient(180deg, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0.6) 100%)" }} />
          <span className="eyebrow" style={{ position: "relative", zIndex: 2, color: "#fff" }}>{tb.featured_brief.toUpperCase()}</span>
          <div className="bf-brand" style={{ position: "relative", zIndex: 2, color: "#fff" }}>{featured.brand}</div>
          <div className="bf-title" style={{ position: "relative", zIndex: 2, color: "#fff" }}>{featured.title[locale]}</div>
        </div>
        <div className="brief-featured-meta">
          <p className="display-italic" style={{ color: "var(--smoke)", margin: 0 }}>{featured.desc[locale]}</p>
          <div className="brief-featured-stats">
            <BriefStat label={tb.payout} value={featured.payout[locale]} highlight />
            <BriefStat label={tb.deadline} value={`${featured.deadline_days} days`} />
            <BriefStat label={tb.duration} value={featured.duration} />
            <BriefStat label={tb.submissions} value={featured.submissions} />
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn btn-primary" onClick={() => onOpenBrief(featured.id)}>
              {tb.details} <Icon name="arrow-right" size={14} />
            </button>
            <window.SaveBtn kind="brief" id={featured.id} label="Save" savedLabel="Saved" />
          </div>
        </div>
      </div>

      {/* Filter row */}
      <div className="brief-filters">
        <div className="bf-group">
          <span className="bf-group-label">{tb.filter_pillar}</span>
          <div className="bf-pills">
            <FilterPill on={pillar === "all"} onClick={() => setPillar("all")}>{t.course.all}</FilterPill>
            {Object.entries(window.PILLARS).map(([k, p]) => (
              <FilterPill key={k} on={pillar === k} onClick={() => setPillar(k)}
                color={p.color} soft={p.soft}>
                {p.name[locale]}
              </FilterPill>
            ))}
          </div>
        </div>

      </div>

      {/* Brief grid */}
      <div className="brief-grid">
        {list.map(b => <BriefCard key={b.id} brief={b} locale={locale} onOpen={() => onOpenBrief(b.id)} />)}
      </div>
    </div>
  );
}

function BriefStat({ label, value, highlight }) {
  return (
    <div className={"brief-stat " + (highlight ? "high" : "")}>
      <div className="brief-stat-label">{label}</div>
      <div className="brief-stat-value">{value}</div>
    </div>
  );
}

function FilterPill({ on, onClick, children, color, soft }) {
  const style = on && color ? { background: soft, color, borderColor: color } : {};
  return (
    <button className={"filter-pill " + (on ? "on" : "")} style={style} onClick={onClick}>
      {children}
    </button>
  );
}

function BriefCard({ brief, locale, onOpen, layout }) {
  const t = window.I18N[locale];
  const tb = t.briefs;
  const pillar = window.PILLARS[brief.pillar];
  const urgent = brief.deadline_days <= 7;
  const claim = (window.BRIEF_CLAIMS && window.BRIEF_CLAIMS[brief.id]);
  const claimLab = claim && claim.status !== "open"
    ? (claim.status === "claimed" ? (locale === "de" ? "Ausgezeichnet" : locale === "id" ? "Dimenangkan" : "Awarded")
      : claim.status === "submitted" ? (locale === "de" ? "In Prüfung" : locale === "id" ? "Sedang ditinjau" : "Under review")
      : null)
    : null;
  const briefImg = briefImageFor(brief.id);
  return (
    <button className={"brief-card " + (layout === "list" ? "list" : "")} onClick={onOpen}>
      <div className="brief-card-stripe" style={{ background: pillar.color }} />
      {layout !== "list" && (
        <div className="brief-card-cover" style={{ position: "relative", overflow: "hidden" }}>
          <img src={briefImg} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          <div style={{ position: "absolute", inset: 0, background: `linear-gradient(180deg, transparent 40%, ${pillar.color}cc 100%)` }} />
          {claimLab && (
            <span className={"claim-pill " + claim.status}>
              <Icon name={claim.status === "submitted" ? "check" : "award"} size={10} /> {claimLab}
            </span>
          )}
        </div>
      )}
      <div className="brief-card-body">
        <div className="brief-card-head">
          <span className="brief-card-brand">{brief.brand}</span>
          <span className="brief-pill" style={{ background: pillar.soft, color: pillar.color }}>
            {pillar.name[locale]}
          </span>
          {layout === "list" && claimLab && (
            <span className={"claim-pill " + claim.status}>
              <Icon name={claim.status === "submitted" ? "check" : "award"} size={10} /> {claimLab}
            </span>
          )}
        </div>
        <div className="brief-card-title">{brief.title[locale]}</div>
        <p className="brief-card-desc subtle">{brief.desc[locale]}</p>

        <div className="brief-card-markets">
          <span className="subtle">{tb.market}:</span>
          {brief.market.map(m => <span key={m} className="m-flag" title={window.I18N[m].market}>{window.I18N[m].flag}</span>)}
        </div>

        <div className="brief-card-foot">
          <div className="brief-card-payout">{brief.payout[locale]}</div>
          <div className="brief-card-meta">
            <span className={"brief-deadline " + (urgent ? "urgent" : "")}><Icon name="clock" size={11} /> {brief.deadline_days}d</span>
            <span className="subtle">·</span>
            <span className="subtle">{brief.duration}</span>
            <span className="subtle">·</span>
            <span className="subtle">{brief.submissions} {tb.submissions}</span>
          </div>
        </div>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────
// Brief detail + submission
// ─────────────────────────────────────────────────────────
function BriefDetail({ briefId, locale, onBack, onSubmit, onOpenAbout, onOpenCvModule, submitOpen: submitOpenProp, submitStep: submitStepProp, onSubmitOpenChange, onSubmitStepChange }) {
  const t = window.I18N[locale];
  const tb = t.briefs;
  const brief = window.BRIEFS.find(b => b.id === briefId) || window.BRIEFS[0];
  const pillar = window.PILLARS[brief.pillar];
  const [submitOpenLocal, setSubmitOpenLocal] = useStateBr(false);
  // Prefer the lifted (URL-addressable) state from App; fall back to local.
  const submitOpen = submitOpenProp !== undefined ? submitOpenProp : submitOpenLocal;
  const setSubmitOpen = (v) => {
    const next = typeof v === "function" ? v(submitOpen) : v;
    if (onSubmitOpenChange) onSubmitOpenChange(next); else setSubmitOpenLocal(next);
  };

  return (
    <div className="page page-brief-detail">
      <div className="player-crumbs">
        <button className="link-btn" onClick={onBack}><Icon name="chevron-left" size={12} /> {tb.heading}</button>
        <span className="crumb-sep">/</span>
        <span className="display-italic" style={{ color: "var(--smoke)" }}>{brief.brand}</span>
      </div>

      <div className="brief-detail-grid">
        <div className="brief-detail-main">
          <div className="brief-detail-hero" style={{ background: `linear-gradient(135deg, ${pillar.color}, var(--squid-ink))` }}>
            <img src={briefImageFor(brief.id)} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.7, zIndex: 0, borderRadius: 14 }} />
            <div style={{ position: "absolute", inset: 0, borderRadius: 14, zIndex: 1, background: "linear-gradient(180deg, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0.55) 100%)" }} />
            <span className="brief-pill" style={{ position: "relative", zIndex: 2, background: "rgba(255,255,255,0.2)", color: "#fff", borderColor: "rgba(255,255,255,0.3)" }}>
              {pillar.name[locale]}
            </span>
            <div className="bdh-brand" style={{ position: "relative", zIndex: 2, color: "#fff" }}>{brief.brand}</div>
            <h1 className="bdh-title" style={{ position: "relative", zIndex: 2, color: "#fff" }}>{brief.title[locale]}</h1>
            <div className="bdh-markets" style={{ position: "relative", zIndex: 2 }}>
              {brief.market.map(m => (
                <span key={m} className="bdh-market">
                  {window.I18N[m].flag} {window.I18N[m].market}
                </span>
              ))}
            </div>
          </div>

          <div className="brief-block">
            <span className="eyebrow">THE BRIEF</span>
            <p className="body-text">{brief.desc[locale]}</p>
          </div>

          <div className="brief-block">
            <span className="eyebrow">DELIVERABLES</span>
            <ul className="brief-list">
              {brief.deliverables.map((d, i) => (
                <li key={i}><Icon name="check-circle" size={14} style={{ color: "var(--ufs-orange)" }} /> {d}</li>
              ))}
            </ul>
          </div>

          <div className="brief-block">
            <span className="eyebrow">TONE</span>
            <p className="body-text">{brief.tone}</p>
          </div>

          <div className="brief-block">
            <span className="eyebrow">DO'S & DON'TS</span>
            <div className="dos-dont">
              <div className="dos">
                <div className="dd-h"><Icon name="check" size={13} /> Do</div>
                <ul>
                  <li>Use the product visibly in at least one shot</li>
                  <li>Speak in your own voice — your team's energy</li>
                  <li>Caption in your region language</li>
                </ul>
              </div>
              <div className="donts">
                <div className="dd-h"><Icon name="x" size={13} /> Don't</div>
                <ul>
                  <li>Use competitor products in frame</li>
                  <li>Add licensed music without clearance</li>
                  <li>Submit late — deadline is firm</li>
                </ul>
              </div>
            </div>
          </div>

          <div className="brief-block">
            <span className="eyebrow">RECOMMENDED TRAININGS</span>
            <div className="rec-mods">
              {(() => {
                const cur = window.CURRICULUM || [];
                // Briefs are best supported by the briefs module + the content-creation hub.
                const recIds = ["m5", "m3"];
                const lessonsLab = locale === "de" ? "Lektionen" : locale === "id" ? "pelajaran" : "lessons";
                const partsLab = locale === "de" ? "Teile" : locale === "id" ? "bagian" : "parts";
                return recIds.map(id => {
                  const m = cur.find(x => x.id === id);
                  if (!m) return null;
                  const lessons = window.moduleLessonCount ? window.moduleLessonCount(m) : 0;
                  const subCount = (m.subModules || []).length;
                  const sub = subCount > 0
                    ? `${lessons} ${lessonsLab} · ${subCount} ${partsLab}`
                    : `${lessons} ${lessonsLab}`;
                  return (
                    <RecMod
                      key={id}
                      title={m.title[locale] || m.title.en}
                      sub={sub}
                      onClick={() => onOpenCvModule && onOpenCvModule(m.id)}
                    />
                  );
                });
              })()}
            </div>
          </div>

          {/* Light recap — links back to the platform-level About UFS */}
          <button className="brief-recap brief-recap-inline" onClick={() => onOpenAbout && onOpenAbout()}>
            <div className="brief-recap-ic"><Icon name="info" size={16} /></div>
            <div className="brief-recap-body">
              <div className="brief-recap-title">{locale === "de" ? "Auffrischung: wer wir sind & wie Briefings funktionieren" : locale === "id" ? "Pengingat: siapa kami & cara kerja brief" : "Recap: who we are & how briefs work"}</div>
            </div>
            <span className="brief-recap-cta">{locale === "de" ? "Ansehen" : locale === "id" ? "Lihat" : "View"} <Icon name="arrow-right" size={13} /></span>
          </button>
        </div>

        <aside className="brief-detail-side">
          <div className="brief-side-card">
            <div className="bsc-payout">
              <span className="eyebrow">{tb.payout.toUpperCase()}</span>
              <div className="bsc-amount">{brief.payout[locale]}</div>
              <div className="subtle">{locale === "de" ? "bei Freigabe" : locale === "id" ? "saat disetujui" : "on approval"}</div>
            </div>
            <div className="bsc-rows">
              <BriefSideRow label={tb.deadline} value={`${brief.deadline_days} days`} accent={brief.deadline_days <= 7} />
              <BriefSideRow label={tb.duration} value={brief.duration} />
              <BriefSideRow label={tb.submissions} value={brief.submissions} />
              <BriefSideRow label={tb.market} value={brief.market.map(m => window.I18N[m].flag).join(" ")} />
            </div>

            {(() => {
              const claim = (window.BRIEF_CLAIMS && window.BRIEF_CLAIMS[brief.id]) || { status: "open" };
              // AWARDED (status "claimed") → chef's submission was approved and the award granted.
              if (claim.status === "claimed") {
                return (
                  <div className="bsc-state bsc-state-awarded">
                    <div className="bsc-state-ic"><Icon name="award" size={20} /></div>
                    <div className="bsc-state-title">{locale === "de" ? "Ausgezeichnet" : locale === "id" ? "Dimenangkan" : "Awarded"}</div>
                    <div className="bsc-state-award">{brief.payout[locale]}</div>
                    <div className="bsc-state-sub">{locale === "de" ? "Deine Einreichung wurde angenommen." : locale === "id" ? "Karyamu telah disetujui." : "Your submission was approved."}</div>
                  </div>
                );
              }
              // SUBMITTED → in review, no submit button
              if (claim.status === "submitted") {
                return (
                  <div className="bsc-state bsc-state-submitted">
                    <div className="bsc-state-ic"><Icon name="check" size={18} /></div>
                    <div className="bsc-state-title">{locale === "de" ? "In Prüfung" : locale === "id" ? "Sedang ditinjau" : "Under review"}</div>
                    <div className="bsc-state-sub">{locale === "de" ? "In Prüfung bei UFS." + (claim.when ? " · " + claim.when : "") : locale === "id" ? "Sedang ditinjau UFS." + (claim.when ? " · " + claim.when : "") : "Awaiting review by UFS." + (claim.when ? " · " + claim.when : "")}</div>
                  </div>
                );
              }
              // OPEN → standard submit + save
              return (
                <>
                  <button className="btn btn-primary btn-block" onClick={() => setSubmitOpen(true)}>
                    <Icon name="upload" size={14} /> {tb.apply}
                  </button>
                  <window.SaveBtn kind="brief" id={brief.id} label="Save for later" savedLabel="Saved" className="btn-block" />
                  <div className="bsc-note">
                    {locale === "de" ? "Offener Marktplatz · mehrere Köche können einreichen. UFS wählt eine oder mehrere für ihre Kanäle." : locale === "id" ? "Marketplace terbuka · beberapa chef bisa mengirim. UFS memilih satu atau lebih untuk kanal mereka." : "Open marketplace · multiple chefs may submit. UFS picks one or more for their channels."}
                  </div>
                </>
              );
            })()}
          </div>
        </aside>
      </div>

      {submitOpen && <SubmitDialog brief={brief} locale={locale} stepProp={submitStepProp} onStepChange={onSubmitStepChange} onClose={() => setSubmitOpen(false)} onSubmitted={() => { setSubmitOpen(false); onSubmit && onSubmit(); }} />}
    </div>
  );
}

function BriefSideRow({ label, value, accent }) {
  return (
    <div className="bsc-row">
      <span className="subtle">{label}</span>
      <span className={"bsc-row-val " + (accent ? "accent" : "")}>{value}</span>
    </div>
  );
}

function RecMod({ title, sub, onClick }) {
  return (
    <button className="rec-mod" onClick={onClick} style={{ width: "100%", textAlign: "left", border: 0, background: "transparent", cursor: onClick ? "pointer" : "default", padding: 0 }}>
      <div className="rec-mod-cover" style={{ background: "linear-gradient(135deg,#ff8a3d,#cc4400)" }}>
        <Icon name="play" size={14} style={{ color: "#fff" }} />
      </div>
      <div>
        <div className="rec-mod-title">{title}</div>
        <div className="subtle">{sub}</div>
      </div>
      {onClick && <Icon name="chevron-right" size={16} style={{ color: "var(--mushroom)", marginLeft: "auto" }} />}
    </button>
  );
}

function SubmitDialog({ brief, locale, onClose, onSubmitted, stepProp, onStepChange }) {
  const [stepLocal, setStepLocal] = useStateBr(stepProp || 1);
  const step = stepProp !== undefined && stepProp !== null ? stepProp : stepLocal;
  const setStep = (v) => {
    const next = typeof v === "function" ? v(step) : v;
    if (onStepChange) onStepChange(next); else setStepLocal(next);
  };
  const [caption, setCaption] = useStateBr("");
  const [hashtags, setHashtags] = useStateBr("");

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <span className="eyebrow">SUBMIT TO BRIEF</span>
            <h2 style={{ margin: "4px 0 0" }}>{brief.title[locale]}</h2>
          </div>
          <button className="icon-btn ghost" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div className="modal-progress">
          {["Upload", "Captions", "Review"].map((label, i) => (
            <div key={i} className={"mp-step " + (step >= i + 1 ? "on" : "")}>
              <div className="mp-num">{step > i + 1 ? <Icon name="check" size={11} /> : i + 1}</div>
              <span>{label}</span>
            </div>
          ))}
        </div>

        <div className="modal-body">
          {step === 1 && (
            <>
              <div className="upload-zone">
                <Icon name="upload" size={28} style={{ color: "var(--smoke)" }} />
                <div className="upload-h">Drop your video, or click to browse</div>
                <div className="subtle">MP4 or MOV · vertical 9:16 · up to 500 MB</div>
                <button className="btn btn-outline" style={{ marginTop: 12 }}>Choose file</button>
              </div>
            </>
          )}
          {step === 2 && (
            <>
              <div className="ob-form">
                <label className="ob-field">
                  <span className="ob-field-label">Caption ({window.I18N[locale].locale})</span>
                  <textarea rows={4} value={caption} onChange={e => setCaption(e.target.value)}
                    placeholder={locale === "de"
                      ? "Zwei Sätze, die das Gericht und deinen Twist beschreiben…"
                      : locale === "id"
                      ? "Dua kalimat yang gambarkan hidangan dan twist-mu…"
                      : "Two sentences that describe the dish and your twist…"} />
                </label>
                <label className="ob-field">
                  <span className="ob-field-label">Hashtags (5 max)</span>
                  <input value={hashtags} onChange={e => setHashtags(e.target.value)} placeholder="#chefverse #knorr #broth …" />
                </label>
              </div>
            </>
          )}
          {step === 3 && (
            <div className="review">
              <div className="review-thumb" style={{ background: `linear-gradient(135deg, ${window.PILLARS[brief.pillar].color}, var(--squid-ink))` }}>
                <Icon name="play" size={28} style={{ color: "#fff" }} />
              </div>
              <div className="review-rows">
                <div className="rev-row"><span className="subtle">Brief</span><span>{brief.title[locale]}</span></div>
                <div className="rev-row"><span className="subtle">Region</span><span>{window.I18N[locale].flag} {window.I18N[locale].market}</span></div>
                <div className="rev-row"><span className="subtle">Caption</span><span style={{ maxWidth: 280, textAlign: "right" }}>{caption || "—"}</span></div>
                <div className="rev-row"><span className="subtle">Hashtags</span><span>{hashtags || "—"}</span></div>
                <div className="rev-row"><span className="subtle">Eligible award on approval</span><span style={{ color: "var(--ufs-orange)", fontWeight: 700 }}>{brief.payout[locale]}</span></div>
              </div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <button className="btn btn-ghost" disabled={step === 1} onClick={() => setStep(s => s - 1)}>Back</button>
          {step < 3 ? (
            <button className="btn btn-primary" onClick={() => setStep(s => s + 1)}>Continue <Icon name="arrow-right" size={12} /></button>
          ) : (
            <button className="btn btn-primary" onClick={onSubmitted}><Icon name="send" size={12} /> Submit to UFS</button>
          )}
        </div>
      </div>
    </div>
  );
}

window.Briefs = Briefs;
window.BriefDetail = BriefDetail;
