// Recursive MLS — live compliance & tips panel for the listing editor.
// Mirrors StepTipsPanel.vue + ListingViolations from the source repo:
// a live 0–100% readiness score, hard violations (must fix) above
// best-practice tips, each with a severity chip, reason, and jump-to-step.
function CompliancePanel({ violations, tips, onJump }) {
  const C = window.RC_COMPLIANCE;
  const [openRules, setOpenRules] = useState(false);

  const totalRules = C.ALL_VIOLATIONS.length + 8; // violations + tip rules
  const issues = violations.length + tips.length;
  const score = Math.round(((totalRules - issues) / totalRules) * 100);
  const highVios = violations.filter((v) => v.severity === "high").length;

  const headTone = violations.length ? "#b3261e" : tips.length ? "#c0612f" : "#1f8a5b";
  const headBg = violations.length ? "#fbe9e7" : tips.length ? "#faf0e8" : "#e8f4ee";
  const scoreColor = score < 60 ? "#b3261e" : score < 85 ? "#9a6a12" : "#1f8a5b";

  const Item = ({ it, colors, hard }) => {
    const c = colors[it.severity];
    return (
      <div className="rc-row" onClick={() => onJump && onJump(it.step)}
        style={{ display: "flex", gap: 11, alignItems: "flex-start", padding: "11px 16px", cursor: "pointer", borderTop: "1px solid #f4f3ee" }}>
        <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", color: c.fg, background: c.bg, borderRadius: 4, padding: "3px 6px", flex: "none", minWidth: 50, textAlign: "center", marginTop: 1 }}>{it.severity}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{it.label}</div>
          <div style={{ fontSize: 12, color: "#8a8e88", lineHeight: 1.45, marginTop: 2 }}>{it.reason}</div>
        </div>
        <Icon name="chevron-right" size={15} color="#c4c7c1" style={{ marginTop: 2 }} />
      </div>
    );
  };

  return (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
      {/* header + score */}
      <div style={{ padding: "14px 16px", borderBottom: "1px solid #f1f0ea" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 11 }}>
          <span style={{ width: 26, height: 26, borderRadius: "50%", background: headBg, display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
            <Icon name={violations.length ? "shield-alert" : tips.length ? "lightbulb" : "shield-check"} size={15} color={headTone} />
          </span>
          <h2 style={{ margin: 0, fontSize: 14.5, fontWeight: 600, color: "#1d241f", flex: 1 }}>MLS compliance</h2>
          <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 15, fontWeight: 700, color: scoreColor }}>{score}%</span>
        </div>
        <div style={{ height: 6, borderRadius: 3, background: "#eeede7", overflow: "hidden" }}>
          <div style={{ width: `${score}%`, height: "100%", background: scoreColor, transition: "width .3s, background .3s" }} />
        </div>
        <div style={{ display: "flex", gap: 14, marginTop: 9, fontSize: 11.5 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: violations.length ? "#b3261e" : "#8a8e88", fontWeight: 600 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: violations.length ? "#b3261e" : "#cfd2cc" }} />
            {violations.length} {violations.length === 1 ? "violation" : "violations"}
          </span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: tips.length ? "#c0612f" : "#8a8e88", fontWeight: 600 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: tips.length ? "#d97757" : "#cfd2cc" }} />
            {tips.length} {tips.length === 1 ? "tip" : "tips"}
          </span>
        </div>
      </div>

      {/* all clear */}
      {!violations.length && !tips.length && (
        <div style={{ padding: "16px", display: "flex", alignItems: "center", gap: 9, color: "#1f8a5b", fontSize: 13 }}>
          <Icon name="badge-check" size={17} color="#1f8a5b" /> Compliant and ready to publish.
        </div>
      )}

      {/* violations first (must fix) */}
      {violations.length > 0 && (
        <div>
          <div style={{ padding: "9px 16px 7px", fontSize: 10, fontWeight: 700, letterSpacing: "1px", textTransform: "uppercase", color: "#b3261e", background: "#fdf4f3" }}>Must fix before publishing</div>
          {violations.map((v) => <Item key={v.id} it={v} colors={C.VIO_COLORS} hard />)}
        </div>
      )}

      {/* tips */}
      {tips.length > 0 && (
        <div>
          <div style={{ padding: "9px 16px 7px", fontSize: 10, fontWeight: 700, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", background: "#faf9f5", borderTop: violations.length ? "1px solid #f1f0ea" : "none" }}>Recommended</div>
          {tips.map((t) => <Item key={t.id} it={t} colors={C.TIP_COLORS} />)}
        </div>
      )}

      {/* rules reference */}
      <div style={{ borderTop: "1px solid #f1f0ea" }}>
        <button onClick={() => setOpenRules(!openRules)} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", background: "transparent", border: 0, padding: "11px 16px", cursor: "pointer", fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#006747" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name="shield-search" size={14} color="#006747" /> Compliance rules enforced</span>
          <Icon name={openRules ? "chevron-up" : "chevron-down"} size={15} color="#006747" />
        </button>
        {openRules && (
          <div style={{ padding: "0 16px 14px" }}>
            {C.ALL_VIOLATIONS.map((r) => {
              const c = C.VIO_COLORS[r.severity];
              return (
                <div key={r.id} style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "8px 0", borderTop: "1px solid #f4f3ee" }}>
                  <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", color: c.fg, background: c.bg, borderRadius: 4, padding: "2px 5px", flex: "none", minWidth: 46, textAlign: "center", marginTop: 1 }}>{r.severity}</span>
                  <div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>{r.label}</div>
                    <div style={{ fontSize: 11.5, color: "#8a8e88", lineHeight: 1.4, marginTop: 1 }}>{r.reason}</div>
                  </div>
                </div>
              );
            })}
            <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 9 }}>Based on NAR Model MLS Rules and common MLS compliance standards.</div>
          </div>
        )}
      </div>
    </div>
  );
}

// Living-Area confidence badge + certify override (mock of /verify-sqft gate).
function SqftConfidence({ result, certified, onCertify }) {
  if (!result || result.state !== "done" || !result.sources.length) return null;
  const ok = result.score >= window.RC_COMPLIANCE.SQFT_MIN;
  const color = ok ? "#1f8a5b" : "#b3261e";
  const bg = ok ? "#e8f4ee" : "#fbe9e7";
  return (
    <div style={{ borderRadius: 6, background: bg, padding: "9px 11px", display: "flex", flexDirection: "column", gap: 7 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Icon name={ok ? "shield-check" : "shield-alert"} size={15} color={color} />
        <span style={{ fontSize: 12.5, fontWeight: 600, color }}>{ok ? "Square footage verified" : "Square footage unverified"}</span>
        <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 12.5, fontWeight: 700, color, marginLeft: "auto" }}>{result.score}% confidence</span>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {result.sources.map((s) => (
          <span key={s.name} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "#4a504a", background: "#fff", border: "1px solid rgba(0,0,0,.08)", borderRadius: 4, padding: "2px 7px" }}>
            <Icon name={s.confirms ? "check" : "x"} size={11} color={s.confirms ? "#1f8a5b" : "#c0612f"} />
            {s.name} · {s.value.toLocaleString()}
          </span>
        ))}
      </div>
      {!ok && (
        <label style={{ display: "flex", alignItems: "flex-start", gap: 8, cursor: "pointer", marginTop: 1 }}>
          <input type="checkbox" checked={certified} onChange={(e) => onCertify(e.target.checked)} style={{ marginTop: 2, accentColor: "#006747" }} />
          <span style={{ fontSize: 11.5, color: "#6b706a", lineHeight: 1.4 }}>I certify this square footage is correct. <span style={{ color: "#9a6a12" }}>Logs an audit flag for admin review.</span></span>
        </label>
      )}
    </div>
  );
}

Object.assign(window, { CompliancePanel, SqftConfidence });
