// report.jsx — Creator report screen (ReportBody is reused in the example section)

const { useEffect: useEffectR, useState: useStateR, useMemo: useMemoR } = React;

function ScoreRing({ score, color, size = 140, stroke = 10, animate = true }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(100, score)) / 100;
  const offset = c * (1 - pct);

  const [progress, setProgress] = useStateR(animate ? 0 : pct);
  useEffectR(() => {
    if (!animate) { setProgress(pct); return; }
    const t = setTimeout(() => setProgress(pct), 60);
    return () => clearTimeout(t);
  }, [pct, animate]);

  const animOffset = c * (1 - progress);

  return (
    <div className="score-ring-wrap" style={{ width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle
          cx={size / 2} cy={size / 2} r={r}
          stroke="var(--bg-tint)" strokeWidth={stroke} fill="none"
        />
        <circle
          cx={size / 2} cy={size / 2} r={r}
          stroke={color} strokeWidth={stroke} fill="none"
          strokeLinecap="round"
          strokeDasharray={c}
          strokeDashoffset={animOffset}
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
          style={{ transition: "stroke-dashoffset 1.1s cubic-bezier(.2,.7,.1,1)" }}
        />
      </svg>
      <div className="num" style={{ color }}>{score}</div>
    </div>
  );
}

function barColor(v) {
  if (v >= 70) return "var(--green)";
  if (v >= 40) return "var(--amber)";
  return "var(--red)";
}

function sevColor(s) {
  if (s === "low") return "var(--green)";
  if (s === "medium") return "var(--amber)";
  return "var(--red)";
}

function ProfileAvatar({ username, displayName }) {
  const [a, b, c] = window.VF.avatarGradient(username);
  const letter = (displayName || username || "?").trim()[0].toUpperCase();
  return (
    <div
      className="avatar"
      style={{ background: `linear-gradient(135deg, ${a}, ${b} 50%, ${c})` }}
    >{letter}</div>
  );
}

function PlatformBadge({ platform }) {
  const { InstagramIcon, TikTokIcon } = window.VFIcons;
  const isIG = platform === "instagram";
  return (
    <span className="platform-badge">
      {isIG ? <InstagramIcon size={12} stroke={1.8} /> : <TikTokIcon size={12} stroke={1.8} />}
      {isIG ? "Instagram" : "TikTok"}
    </span>
  );
}

function fmt(n) { return window.VF.formatCount(n); }

function ReportBody({ report, compact = false, onAction }) {
  const { HeartIcon, MessageIcon, UsersIcon, DownloadIcon, CompareIcon, BookmarkIcon } = window.VFIcons;
  const bd = report.breakdown;
  const rows = [
    { key: "engagementConsistency", label: "Engagement consistency", v: bd.engagementConsistency },
    { key: "commentQuality",        label: "Comment quality",         v: bd.commentQuality },
    { key: "audienceQuality",       label: "Audience quality",        v: bd.audienceQuality },
    { key: "sponsoredPerformance",  label: "Sponsored performance",   v: bd.sponsoredPerformance },
    { key: "followerStability",     label: "Follower stability",      v: bd.followerStability },
  ];
  const ringSize = compact ? 120 : 140;

  // For mounted-animation effect (re-runs when score changes)
  const [tick, setTick] = useStateR(0);
  useEffectR(() => { setTick(t => t + 1); }, [report.username, report.platform]);

  return (
    <div key={tick} className="fade-up">
      <div className="profile-head" style={compact ? { marginBottom: 28 } : {}}>
        <ProfileAvatar username={report.username} displayName={report.displayName} />
        <div className="profile-meta">
          <h1>@{report.username} <PlatformBadge platform={report.platform} /></h1>
          <div className="name">{report.displayName}{report.bio ? ` · ${report.bio}` : ""}</div>
        </div>
      </div>

      <div className="score-card" style={compact ? { padding: "36px 28px" } : {}}>
        <ScoreRing score={report.displayScore} color={report.band.color} size={ringSize} />
        <div className="score-band">
          <span className="dot" style={{ background: report.band.color }}></span>
          <span style={{ color: report.band.color }}>{report.band.label}</span>
        </div>
        <div className="score-summary">{report.summary}</div>
      </div>

      <div className="metrics-row">
        <div className="metric">
          <div className="label"><UsersIcon size={13} stroke={1.8} style={{ verticalAlign: -2, marginRight: 4 }} />Followers</div>
          <div className="value">{fmt(report.followers)}</div>
          <div className="sub">Public profile</div>
        </div>
        <div className="metric">
          <div className="label"><HeartIcon size={13} stroke={1.8} style={{ verticalAlign: -2, marginRight: 4 }} />Avg likes</div>
          <div className="value">{fmt(report.avgLikes)}</div>
          <div className="sub mono">{report.engagementRate}% engagement</div>
        </div>
        <div className="metric">
          <div className="label"><MessageIcon size={13} stroke={1.8} style={{ verticalAlign: -2, marginRight: 4 }} />Avg comments</div>
          <div className="value">{fmt(report.avgComments)}</div>
          <div className="sub mono">{(report.avgComments / report.avgLikes * 100).toFixed(1)}% of likes</div>
        </div>
      </div>

      <div className="section-title">Score breakdown</div>
      <div className="breakdown-card">
        {rows.map((r) => (
          <div className="bar-row" key={r.key}>
            <div className="bar-head">
              <span>{r.label}</span>
              <span className="v mono">{r.v}</span>
            </div>
            <div className="bar-track">
              <div
                className="bar-fill"
                style={{ width: `${r.v}%`, background: barColor(r.v) }}
              ></div>
            </div>
          </div>
        ))}
      </div>

      <div className="section-title">Signals</div>
      <div>
        {report.signals.map((s, i) => (
          <div className="signal-card" key={i}>
            <span className="signal-dot" style={{ background: sevColor(s.severity) }}></span>
            <div>
              <div className="signal-title">{s.title}</div>
              <div className="signal-body">{s.body}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="section-title">Deal recommendation</div>
      <div className="rec-card">
        <div className="label">Suggested approach</div>
        <div className="verdict">{report.recommendation.verdict}</div>
        <div className="body">{report.recommendation.body}</div>
      </div>

      {!compact && (
        <div className="actions">
          <button className="btn btn--primary"><DownloadIcon size={16} stroke={2} /> Export report</button>
          <button className="btn"><CompareIcon size={16} stroke={2} /> Compare creators</button>
          <button className="btn"><BookmarkIcon size={16} stroke={2} /> Track this creator</button>
        </div>
      )}
    </div>
  );
}

function ReportScreen({ report, onBack, onSearch }) {
  const { ArrowLeft } = window.VFIcons;
  return (
    <div className="report">
      <div className="report-top">
        <button onClick={onBack}><ArrowLeft size={16} stroke={2} /> New search</button>
      </div>
      <ReportBody report={report} />
    </div>
  );
}

Object.assign(window, { ScoreRing, ReportBody, ReportScreen, ProfileAvatar, PlatformBadge });
