// Distro comparison UI: producer cheat sheet, badges, full matrix

const DISTRO_ACRONYMS = new Set([
  "UGC", "ID", "PRO", "ACH", "UK", "US", "VEVO", "DSP", "ISRC", "UPC",
  "PST", "EST", "VK", "GB", "BR", "AU", "NZ", "CID", "JOOX", "KKBOX",
]);

const DISTRO_EXACT = {
  yes: "Yes",
  no: "No",
  "n/a": "N/A",
  unknown: "Unknown",
  immediate: "Immediate",
};

function formatDistroText(str) {
  if (!str || str === "N/A") return str;
  const trimmed = String(str).trim();
  const exact = DISTRO_EXACT[trimmed.toLowerCase()];
  if (exact) return exact;

  return trimmed.replace(/[A-Za-z][A-Za-z']*/g, (word) => {
    const upper = word.toUpperCase();
    if (DISTRO_ACRONYMS.has(upper)) return upper;
    if (word.length <= 4 && /^[A-Z]+$/.test(word)) return word;
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
}

const PRODUCER_SHEET_FIELDS = [
  { key: "paymentSplitting", label: "Payment splitting", highlight: true },
  { key: "commission", label: "Commission" },
  { key: "payment", label: "Payment timing" },
  { key: "paymentThreshold", label: "Payment threshold" },
  { key: "youtubeContentId", label: "YouTube Content ID" },
  { key: "speedSpotify", label: "Speed to Spotify" },
  { key: "speedApple", label: "Speed to Apple Music" },
  { key: "customLabelName", label: "Custom label name" },
  { key: "distributeCredits", label: "Credits distribution" },
  { key: "revenueReports", label: "Revenue reports" },
  { key: "supportEmail", label: "Support turnaround" },
  { key: "coverMechanicals", label: "Cover song mechanicals" },
];

function DistroQuickBadges({ profile, commissionPct }) {
  if (!profile || profile.id === "other") return null;
  const splitsOk = profile.splits;
  const payout = profile.producer?.payment || "N/A";
  const commissionLabel = profile.sparse
    ? "unknown"
    : commissionPct === 0
      ? "0% commission"
      : `${commissionPct}% commission`;

  return (
    <div className="distro-badges">
      <span className={`distro-badge${splitsOk ? " distro-badge--ok" : " distro-badge--warn"}`}>
        {splitsOk ? "Splits ✓" : "No splits"}
      </span>
      {!profile.sparse && (
        <span className={`distro-badge${commissionPct === 0 ? " distro-badge--ok" : ""}`}>
          {commissionLabel}
        </span>
      )}
      {!profile.sparse && payout !== "n/a" && payout !== "unknown" && (
        <span className="distro-badge">Payout: {formatDistroText(payout)}</span>
      )}
    </div>
  );
}

function DistroPlanPicker({ profile, tierId, onTierChange }) {
  if (!profile?.commission?.tiers || profile.commission.tiers.length < 2) return null;
  return (
    <div className="distro-plan-picker" style={{ marginTop: 10 }}>
      <span className="caption" style={{ display: "block", marginBottom: 6 }}>Artist plan (affects commission)</span>
      <div className="field-select-wrap">
        <select
          className="field"
          value={tierId || profile.commission.tiers[0].id}
          onChange={(e) => onTierChange(e.target.value)}
        >
          {profile.commission.tiers.map((t) => (
            <option key={t.id} value={t.id} style={{ background: "var(--bg)", color: "var(--ink)" }}>
              {t.label} · {t.pct}% commission
            </option>
          ))}
        </select>
        <span className="field-select-chevron">▼</span>
      </div>
    </div>
  );
}

function DistroProducerSheet({ profile }) {
  if (!profile || profile.id === "other") return null;

  return (
    <div className="distro-sheet">
      {!profile.splits && (
        <div className="distro-sheet-warn">
          No native splits. You'll need a separate agreement or insist the artist switches before release.
        </div>
      )}
      <h4 className="distro-sheet-title">What this means when you're on the split</h4>
      <div className="distro-sheet-grid">
        {PRODUCER_SHEET_FIELDS.map(({ key, label, highlight }) => {
          const val = profile.producer?.[key] ?? "N/A";
          if (val === "n/a" || val === "unknown") return null;
          const isHighlight = highlight && profile.splits;
          return (
            <div key={key} className={`distro-sheet-cell${isHighlight ? " distro-sheet-cell--gold" : ""}`}>
              <span className="distro-sheet-label">{label}</span>
              <span className="distro-sheet-value">{formatDistroText(val)}</span>
            </div>
          );
        })}
        {profile.producer?.publishingAdmin && profile.producer.publishingAdmin !== "n/a" && (
          <div className="distro-sheet-cell">
            <span className="distro-sheet-label">Publishing admin</span>
            <span className="distro-sheet-value">{formatDistroText(profile.producer.publishingAdmin)}</span>
          </div>
        )}
      </div>
      {!profile.sparse && (
        <p className="distro-sheet-attribution">{window.DISTRO_DATA_META?.attribution}</p>
      )}
    </div>
  );
}

function DistroPickerBlock({
  distro,
  setDistro,
  profile,
  tierId,
  setTierId,
  commissionPct,
  selectedColor,
  showSheet = true,
}) {
  const sel = selectedColor || "#d4a64a";
  const profiles = window.DISTRO_PROFILES || [];

  return (
    <div className="distro-picker-block">
      <div className="field-select-wrap">
        <select
          className="field"
          value={distro}
          onChange={(e) => setDistro(e.target.value)}
          style={{ borderColor: profile?.splits ? sel + "66" : undefined }}
        >
          {profiles.map((d) => (
            <option key={d.id} value={d.id} style={{ background: "var(--bg)", color: "var(--ink)" }}>
              {d.label}{d.splits ? "" : " · no splits"}
            </option>
          ))}
        </select>
        <span className="field-select-chevron">▼</span>
      </div>
      <p className="field-help" style={{ marginTop: 10, marginBottom: 0, fontSize: 12, color: profile?.splits ? "var(--ink-2)" : "#e88a7d" }}>
        {profile?.note}
      </p>
      <DistroPlanPicker profile={profile} tierId={tierId} onTierChange={setTierId} />
      <DistroQuickBadges profile={profile} commissionPct={commissionPct} />
      {showSheet && <DistroProducerSheet profile={profile} />}
    </div>
  );
}

function DistroComparisonMatrix({ selectedId, onSelect }) {
  const [view, setView] = React.useState("compare");
  const [search, setSearch] = React.useState("");
  const [filterSplits, setFilterSplits] = React.useState(false);
  const [filterZeroCommission, setFilterZeroCommission] = React.useState(false);
  const [filterFastPayout, setFilterFastPayout] = React.useState(false);
  const [filterContentId, setFilterContentId] = React.useState(false);
  const [compareIds, setCompareIds] = React.useState(() => {
    const base = selectedId && selectedId !== "other" ? [selectedId] : ["distrokid"];
    return base.slice(0, 3);
  });
  const [openCategories, setOpenCategories] = React.useState({ gettingPaid: true });

  React.useEffect(() => {
    if (selectedId && selectedId !== "other" && !compareIds.includes(selectedId)) {
      setCompareIds((prev) => [selectedId, ...prev.filter((id) => id !== selectedId)].slice(0, 3));
    }
  }, [selectedId]);

  const profiles = (window.DISTRO_PROFILES || []).filter((d) => d.id !== "other" && !d.sparse);

  const filtered = profiles.filter((p) => {
    if (search && !p.label.toLowerCase().includes(search.toLowerCase())) return false;
    if (filterSplits && !p.splits) return false;
    if (filterZeroCommission && p.commission.default !== 0) return false;
    if (filterFastPayout && !window.isFastPayout(p)) return false;
    if (filterContentId && !window.hasContentId(p)) return false;
    return true;
  });

  const toggleCompare = (id) => {
    setCompareIds((prev) => {
      if (prev.includes(id)) return prev.filter((x) => x !== id);
      if (prev.length >= 3) return [...prev.slice(1), id];
      return [...prev, id];
    });
  };

  const toggleCategory = (id) => {
    setOpenCategories((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const compareProfiles = compareIds
    .map((id) => window.getDistroProfile(id))
    .filter((p) => p && !p.sparse && p.id !== "other");

  return (
    <div className="distro-matrix">
      <div className="distro-matrix-toolbar">
        <input
          type="search"
          className="distro-matrix-search"
          placeholder="Search distributors…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <div className="distro-matrix-filters">
          {[
            { key: "splits", label: "Has splits", on: filterSplits, set: setFilterSplits },
            { key: "zero", label: "0% commission", on: filterZeroCommission, set: setFilterZeroCommission },
            { key: "fast", label: "Fast payout", on: filterFastPayout, set: setFilterFastPayout },
            { key: "cid", label: "Content ID", on: filterContentId, set: setFilterContentId },
          ].map((f) => (
            <button
              key={f.key}
              type="button"
              className={`distro-matrix-filter${f.on ? " active" : ""}`}
              onClick={() => f.set(!f.on)}
            >
              {f.label}
            </button>
          ))}
        </div>
        <div className="distro-matrix-view-toggle">
          <button type="button" className={view === "compare" ? "active" : ""} onClick={() => setView("compare")}>
            Compare selected
          </button>
          <button type="button" className={view === "browse" ? "active" : ""} onClick={() => setView("browse")}>
            Browse all
          </button>
        </div>
      </div>

      {view === "compare" && (
        <>
          <p className="caption" style={{ marginBottom: 12 }}>
            Select up to 3 distributors to compare. Click a name below to sync with the dropdown above.
          </p>
          <div className="distro-compare-chips">
            {filtered.map((p) => (
              <button
                key={p.id}
                type="button"
                className={`distro-compare-chip${compareIds.includes(p.id) ? " active" : ""}${p.id === selectedId ? " selected" : ""}`}
                onClick={() => toggleCompare(p.id)}
              >
                {p.label}
                {p.splits ? "" : " · no splits"}
              </button>
            ))}
          </div>
          <div className="distro-compare-cards">
            {compareProfiles.map((p) => (
              <div key={p.id} className={`distro-compare-card${p.id === selectedId ? " is-selected" : ""}`}>
                <button type="button" className="distro-compare-card-head" onClick={() => onSelect(p.id)}>
                  <span className="pull-serif" style={{ fontSize: 18 }}>{p.label}</span>
                  {p.id === selectedId && <span className="distro-compare-selected-tag">selected</span>}
                </button>
                <div className="distro-compare-card-body">
                  {PRODUCER_SHEET_FIELDS.map(({ key, label }) => {
                    const val = p.producer?.[key];
                    if (!val || val === "n/a") return null;
                    return (
                      <div key={key} className="distro-compare-row">
                        <span className="distro-compare-label">{label}</span>
                        <span className="distro-compare-val">{formatDistroText(val)}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {view === "browse" && (
        <div className="distro-matrix-accordion">
          {(window.DISTRO_CATEGORIES || []).map((cat) => (
            <div key={cat.id} className="distro-matrix-category">
              <button type="button" className="distro-matrix-category-head" onClick={() => toggleCategory(cat.id)}>
                <span>{cat.label}</span>
                <span>{openCategories[cat.id] ? "▲" : "▼"}</span>
              </button>
              {openCategories[cat.id] && (
                <div className="distro-matrix-scroll">
                  <table className="distro-matrix-table">
                    <thead>
                      <tr>
                        <th className="distro-matrix-sticky">Field</th>
                        {filtered.map((p) => (
                          <th key={p.id} className={p.id === selectedId ? "is-selected" : ""}>
                            <button type="button" onClick={() => onSelect(p.id)}>{p.label}</button>
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {cat.fields.map((field) => (
                        <tr key={field.key}>
                          <td className="distro-matrix-sticky">{field.label}</td>
                          {filtered.map((p) => {
                            const val = p.fields?.[cat.id]?.[field.key] ?? "N/A";
                            return (
                              <td key={p.id} className={p.id === selectedId ? "is-selected" : ""}>{formatDistroText(val)}</td>
                            );
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      <p className="caption distro-sheet-attribution" style={{ marginTop: 20 }}>
        {window.DISTRO_DATA_META?.attribution}
      </p>
    </div>
  );
}

window.DistroPickerBlock = DistroPickerBlock;
window.DistroComparisonMatrix = DistroComparisonMatrix;
window.DistroQuickBadges = DistroQuickBadges;
window.DistroProducerSheet = DistroProducerSheet;
window.DistroPlanPicker = DistroPlanPicker;
