// Compose View — Grammarly for Compliance
// Two-column: draft pillow + glass-red review panel

const ScoreGauge = ({ value = 78, size = 56, clear = false }) => {
  const r = (size - 6) / 2;
  const c = 2 * Math.PI * r;
  const off = c - (value / 100) * c;
  const stroke = clear ? "var(--success-mint)" : "var(--midnight)";
  return (
    <svg width={size} height={size}>
      <circle cx={size/2} cy={size/2} r={r} stroke="var(--gray-whisper)" strokeWidth="3" fill="none"/>
      <circle cx={size/2} cy={size/2} r={r}
        stroke={stroke} strokeWidth="3" fill="none"
        strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
        transform={`rotate(-90 ${size/2} ${size/2})`}
        style={{ transition: "stroke-dashoffset 600ms cubic-bezier(0.16,1,0.3,1), stroke 400ms ease" }}
      />
      <text x="50%" y="52%" textAnchor="middle" dominantBaseline="middle"
        fontFamily="Fraunces, serif" fontSize={size*0.35} fill="var(--midnight)">{value}</text>
    </svg>
  );
};

const ComposeView = ({ width = 1440, height = 900, mode = "before" }) => {
  // mode: "before" | "after" — toggled by Fix-All
  const [fixed, setFixed] = React.useState(mode === "after");
  const [score, setScore] = React.useState(mode === "after" ? 96 : 64);

  React.useEffect(() => { setFixed(mode === "after"); setScore(mode === "after" ? 96 : 64); }, [mode]);

  const fixAll = () => {
    setFixed(true);
    let v = score;
    const target = 96;
    const start = performance.now();
    const tick = () => {
      const k = Math.min(1, (performance.now() - start) / 700);
      const ease = 1 - Math.pow(1 - k, 3);
      setScore(Math.round(v + (target - v) * ease));
      if (k < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  };
  const issues = [
    { sev: "high", color: "#E63946", phrase: "safe and should return 10%", reason: "Implies a guaranteed return. Violates SEC Rule 482 — performance language must include risk disclosures and may not promise specific outcomes.", fix: "may target 8–12% returns over a 3-year horizon, subject to market conditions" },
    { sev: "high", color: "#E63946", phrase: "zero downside", reason: "Absolute claim. Investments cannot have zero downside; FCA requires fair, clear, balanced language.", fix: "limited downside under our base-case scenario" },
    { sev: "mid",  color: "#F4811F", phrase: "outperform the market", reason: "Forward-looking superlative without hedging. SEC requires comparative claims to be qualified.", fix: "we believe it can outperform our benchmark over the medium term" },
    { sev: "low",  color: "#F4C430", phrase: "incredibly stable", reason: "Tone — superlative without basis. Soft suggestion to remove unsupported intensifier.", fix: "stable" },
  ];

  const RiskSpan = ({ children, idx, on }) => {
    return (
      <span className={`risk-mark ${!on ? "fading" : ""}`}
        style={!on ? { background: "transparent", textDecoration: "none" } : undefined}>
        {children}
      </span>
    );
  };

  return (
    <div style={{ width, height, background: "var(--white-pure)", display: "flex", flexDirection: "column", position: "relative", overflow: "hidden" }}>
      {/* Ambient gradient wash on right edge while issues exist */}
      <div style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "linear-gradient(135deg, transparent 60%, rgba(230,57,70,0.05) 100%)",
        opacity: fixed ? 0 : 1, transition: "opacity 800ms ease",
      }}/>

      <TopBar active="Compose"/>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(0, 60fr) minmax(0, 35fr)", gap: 24, padding: 32, minHeight: 0, overflow: "hidden" }}>
        {/* Draft — soft green glow once the draft is fixed */}
        <div className="pillow float-in" style={{
          padding: 36, display: "flex", flexDirection: "column",
          position: "relative", minHeight: 0, minWidth: 0,
          boxShadow: fixed
            ? "0 1px 2px rgba(10,22,40,0.04), 0 12px 32px rgba(52,211,153,0.18), 0 0 0 1px rgba(52,211,153,0.20)"
            : undefined,
          transition: "box-shadow 600ms cubic-bezier(0.16,1,0.3,1)",
        }}>
          {/* Score gauge top-right */}
          <div style={{ position: "absolute", top: 24, right: 24, display: "flex", alignItems: "center", gap: 10 }}>
            <span className="micro" style={{ color: "var(--midnight-soft)" }}>DRAFT SCORE</span>
            <ScoreGauge value={score} clear={fixed}/>
          </div>

          {/* Fields */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14, paddingRight: 110 }}>
            <Field label="To"      value="m.castelli@northwind-cap.com, compliance@redgone.io"/>
            <Field label="Subject" value="Q2 portfolio update — your private allocation"/>
          </div>

          {/* Body */}
          <div style={{ fontSize: 16, lineHeight: 1.7, color: "var(--midnight)", flex: 1, overflow: "auto", minHeight: 0, marginTop: 18 }} className="scroll">
            <p style={{ marginTop: 0 }}>Hi Marco,</p>
            <p>
              Thanks for the call yesterday. I wanted to follow up on the new fund we discussed.
              This investment is{" "}
              <RiskSpan idx={0} on={!fixed}>{fixed ? "may target 8–12% returns over a 3-year horizon, subject to market conditions" : "safe and should return 10%"}</RiskSpan>{" "}
              based on the strategy we walked through. Given current conditions, we expect to{" "}
              <RiskSpan idx={2} on={!fixed}>{fixed ? "we believe it can outperform our benchmark over the medium term" : "outperform the market"}</RiskSpan>{" "}
              while keeping{" "}
              <RiskSpan idx={1} on={!fixed}>{fixed ? "limited downside under our base-case scenario" : "zero downside"}</RiskSpan>.
            </p>
            <p>
              The track record has been{" "}
              <RiskSpan idx={3} on={!fixed}>{fixed ? "stable" : "incredibly stable"}</RiskSpan>{" "}
              and we'd like to walk you through the allocation before quarter close.
              Let me know a time that works.
            </p>
            <p style={{ color: "var(--midnight-soft)" }}>Best,<br/>Sarah</p>
          </div>

          {/* Bottom bar */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 20 }}>
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <button className="neu-btn neu-btn-primary">Send</button>
              <button className="neu-btn">Save draft</button>
            </div>
            <div className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>
              {fixed ? "ALL CLEAR · 0 ISSUES" : `${issues.length} ISSUES · FCA + SEC`}
            </div>
          </div>
        </div>

        {/* Glass review panel */}
        <div style={{ position: "relative", display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
          <div className="glass-red float-in" style={{
            padding: 24, flex: 1, display: "flex", flexDirection: "column",
            minHeight: 0,
            opacity: fixed ? 0 : 1,
            transform: fixed ? "translateY(8px) scale(0.98)" : "none",
            transition: "all 600ms cubic-bezier(0.16,1,0.3,1)",
            pointerEvents: fixed ? "none" : "auto",
          }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div className="micro" style={{ color: "var(--red-deep)" }}>REVIEW</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--red-deep)" }}>{issues.length} ISSUES</div>
            </div>

            <div className="scroll" style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 12, overflow: "auto", flex: 1, minHeight: 0, paddingRight: 4 }}>
              {issues.map((iss, i) => (
                <div key={i} style={{
                  background: "#FFFFFF", borderRadius: 14, padding: 16,
                  boxShadow: "0 1px 2px rgba(10,22,40,.04), 0 4px 14px rgba(10,22,40,.05)",
                  border: "1px solid rgba(10,22,40,0.03)",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 999, background: iss.color, boxShadow: `0 0 0 4px ${iss.color}22` }}/>
                    <span className="micro" style={{ color: "var(--midnight-soft)" }}>{iss.sev === "high" ? "Severity · High" : iss.sev === "mid" ? "Severity · Mid" : "Severity · Low"}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--midnight)", marginBottom: 6 }}>"{iss.phrase}"</div>
                  <div style={{ fontSize: 12.5, lineHeight: 1.55, color: "var(--midnight-soft)" }}>{iss.reason}</div>
                  <div style={{
                    marginTop: 10, padding: "8px 10px", borderRadius: 8,
                    background: "rgba(52, 211, 153, 0.08)", border: "1px solid rgba(52,211,153,0.18)",
                    fontSize: 12, color: "var(--midnight)",
                  }}>
                    <span className="mono" style={{ fontSize: 10, color: "var(--success-mint)", fontWeight: 700, marginRight: 6 }}>SUGGESTED</span>
                    {iss.fix}
                  </div>
                  <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                    <button className="neu-btn neu-btn-primary neu-btn-sm">Fix this</button>
                    <button className="neu-btn neu-btn-sm">Ignore</button>
                  </div>
                </div>
              ))}
            </div>

            <button onClick={fixAll} className="neu-btn-greengrad" style={{
              marginTop: 16, padding: "14px 18px", fontSize: 14,
              justifyContent: "center", width: "100%",
            }}>
              <span>Fix all with RedGone</span>
              <span style={{ opacity: 0.85 }}>→</span>
            </button>
          </div>

          {/* All-clear card after fix — same green glow as the email pillow */}
          {fixed && (
            <div className="pillow float-in" style={{
              position: "absolute", inset: 0, padding: 32,
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 12,
              boxShadow: "0 1px 2px rgba(10,22,40,0.04), 0 18px 44px rgba(16,185,129,0.30), 0 0 0 2px rgba(52,211,153,0.45)",
            }}>
              <AngelRobot size={140} view="front"/>
              <div className="h2" style={{ marginTop: 8 }}>All clear.</div>
              <div className="small" style={{ color: "var(--midnight-soft)", textAlign: "center", maxWidth: 280 }}>
                4 risks rewritten. Your draft score moved from 64 to 96.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, value }) => (
  <div style={{ display: "flex", alignItems: "baseline", gap: 14, borderBottom: "1px solid var(--gray-whisper)", paddingBottom: 10 }}>
    <span className="micro" style={{ width: 70 }}>{label}</span>
    <input
      defaultValue={value}
      style={{
        fontSize: 15, color: "var(--midnight)", flex: 1,
        background: "transparent", border: "none", outline: "none",
        font: "inherit", padding: 0,
      }}
    />
  </div>
);

window.ComposeView = ComposeView;
