/* salary.jsx — AI salary benchmarker by country */

const SALARY_COUNTRIES = [
  { code:"US", label:"United States",      currency:"USD", symbol:"$"  },
  { code:"GB", label:"United Kingdom",     currency:"GBP", symbol:"£"  },
  { code:"CA", label:"Canada",             currency:"CAD", symbol:"CA$"},
  { code:"AU", label:"Australia",          currency:"AUD", symbol:"A$" },
  { code:"DE", label:"Germany",            currency:"EUR", symbol:"€"  },
  { code:"FR", label:"France",             currency:"EUR", symbol:"€"  },
  { code:"NL", label:"Netherlands",        currency:"EUR", symbol:"€"  },
  { code:"SG", label:"Singapore",          currency:"SGD", symbol:"S$" },
  { code:"AE", label:"UAE",                currency:"AED", symbol:"AED"},
  { code:"IN", label:"India",              currency:"INR", symbol:"₹"  },
  { code:"BD", label:"Bangladesh",         currency:"BDT", symbol:"৳"  },
  { code:"PK", label:"Pakistan",           currency:"PKR", symbol:"PKR"},
  { code:"MY", label:"Malaysia",           currency:"MYR", symbol:"RM" },
  { code:"NG", label:"Nigeria",            currency:"NGN", symbol:"₦"  },
  { code:"ZA", label:"South Africa",       currency:"ZAR", symbol:"R"  },
  { code:"BR", label:"Brazil",             currency:"BRL", symbol:"R$" },
  { code:"MX", label:"Mexico",             currency:"MXN", symbol:"MX$"},
  { code:"PH", label:"Philippines",        currency:"PHP", symbol:"₱"  },
  { code:"JP", label:"Japan",              currency:"JPY", symbol:"¥"  },
  { code:"KR", label:"South Korea",        currency:"KRW", symbol:"₩"  },
  { code:"SA", label:"Saudi Arabia",       currency:"SAR", symbol:"SR" },
  { code:"EG", label:"Egypt",              currency:"EGP", symbol:"E£" },
  { code:"KE", label:"Kenya",              currency:"KES", symbol:"KSh"},
  { code:"GH", label:"Ghana",              currency:"GHS", symbol:"GH₵"},
  { code:"TR", label:"Turkey",             currency:"TRY", symbol:"₺"  },
  { code:"ID", label:"Indonesia",          currency:"IDR", symbol:"Rp" },
  { code:"TH", label:"Thailand",           currency:"THB", symbol:"฿"  },
  { code:"VN", label:"Vietnam",            currency:"VND", symbol:"₫"  },
];

function SalaryDrawer({ data, onClose }) {
  const { useState: S, useEffect: E, useMemo: M } = React;
  const [country,  setCountry]  = S("US");
  const [stage,    setStage]    = S("idle");
  const [result,   setResult]   = S(null);
  const [errMsg,   setErrMsg]   = S("");
  const [limitHit, setLimitHit] = S(false);

  E(() => {
    // Auto-detect country from location
    const loc = (data.basics?.location || "").toLowerCase();
    const detected = SALARY_COUNTRIES.find(c =>
      loc.includes(c.label.toLowerCase()) ||
      loc.includes(c.code.toLowerCase()) ||
      loc.includes(c.currency.toLowerCase())
    );
    if (detected) setCountry(detected.code);
  }, [data.basics?.location]);

  E(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Estimate years of experience from experience array
  const yearsExp = M(() => {
    const exp = data.experience || [];
    if (!exp.length) return null;
    let totalMonths = 0;
    exp.forEach(x => {
      const start = x.start ? new Date(x.start) : null;
      const end   = x.end && x.end !== "Present" ? new Date(x.end) : new Date();
      if (start && !isNaN(start)) {
        totalMonths += Math.max(0, (end - start) / (1000 * 60 * 60 * 24 * 30.4));
      }
    });
    return totalMonths > 0 ? Math.round(totalMonths / 12) : null;
  }, [data.experience]);

  const selectedCountry = SALARY_COUNTRIES.find(c => c.code === country);

  const estimate = async () => {
    if (!window.groqStream) { setErrMsg("AI not available."); setStage("error"); return; }
    setStage("loading"); setResult(null); setErrMsg("");

    const role     = data.basics?.title || "Professional";
    const location = data.basics?.location || selectedCountry?.label || "";
    const years    = yearsExp !== null ? yearsExp : "unknown";
    const skills   = (data.skills || []).flatMap(g => g.items || []).slice(0, 10).join(", ");
    const countryLabel = selectedCountry?.label || country;
    const currency    = selectedCountry?.currency || "USD";
    const symbol      = selectedCountry?.symbol || "$";

    let raw = "";
    await window.groqStream({
      messages: [
        { role: "system", content: "You are a compensation expert with deep knowledge of global salary data. Provide realistic, research-based salary estimates." },
        { role: "user", content: `Estimate annual salary range for this professional in ${countryLabel} (${currency}).

Role: ${role}
Location: ${location || countryLabel}
Years of experience: ${years}
Key skills: ${skills}

Return ONLY a JSON object with this exact structure:
{
  "min": 85000,
  "mid": 105000,
  "max": 130000,
  "currency": "${currency}",
  "symbol": "${symbol}",
  "percentile25": 80000,
  "percentile75": 125000,
  "insight": "One sentence on market context — demand, trends, or what drives range variance for this role in ${countryLabel}.",
  "topPayingCities": ["City1", "City2", "City3"]
}

Use realistic annual gross salary in ${currency}. All values must be numbers (no commas or currency symbols in numbers).` },
      ],
      maxTokens: 400,
      onChunk: (_, full) => { raw = full; },
      onDone: () => {
        try {
          let s = raw.trim().replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"");
          const obj = JSON.parse(s.match(/\{[\s\S]*\}/)?.[0] || s);
          setResult(obj);
          setStage("done");
        } catch(_) {
          setErrMsg("Could not parse result. Try again.");
          setStage("error");
        }
      },
      onError: e => { if (e === "free_limit_reached") { setLimitHit(true); } else { setErrMsg(typeof e==="string"?e:"AI error."); } setStage("error"); },
    });
  };

  const fmt = n => {
    if (!n) return "—";
    const sym = result?.symbol || selectedCountry?.symbol || "$";
    if (n >= 1_000_000) return sym + (n/1_000_000).toFixed(1) + "M";
    if (n >= 1_000)     return sym + Math.round(n/1000) + "K";
    return sym + n.toLocaleString();
  };

  const pct = result ? Math.round(((result.mid - result.min) / (result.max - result.min)) * 100) : 50;

  return (
    <>
      <div className="drawer-back" onClick={onClose} />
      <div className="drawer" style={{ width: 430 }}>
        <div className="drawer-h" style={{ display:"flex", alignItems:"center" }}>
          <div>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700, color:"var(--navy)" }}>Salary Benchmarker</h3>
            <p style={{ margin:"3px 0 0", fontSize:12.5, color:"var(--slate-500)" }}>AI-estimated market range for your role</p>
          </div>
          <div style={{ flex:1 }} />
          <button className="x" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="drawer-body scroll" style={{ padding:"20px 20px 28px" }}>

          {/* Role summary */}
          <div style={{ padding:"12px 14px", background:"var(--slate-50)", borderRadius:10, border:"1px solid var(--slate-150,#e8ecf0)", marginBottom:16 }}>
            <div style={{ fontWeight:700, fontSize:14, color:"var(--navy)" }}>{data.basics?.title || "No title set"}</div>
            <div style={{ fontSize:12.5, color:"var(--slate-500)", marginTop:3 }}>
              {yearsExp !== null ? yearsExp + " yrs experience · " : ""}{data.basics?.location || "Location not set"}
            </div>
          </div>

          {/* Country picker */}
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:12, fontWeight:700, color:"var(--slate-600)", textTransform:"uppercase", letterSpacing:".06em", display:"block", marginBottom:7 }}>
              Target country / market
            </label>
            <select className="inp" value={country} onChange={e => setCountry(e.target.value)} style={{ width:"100%", fontSize:13.5 }}>
              {SALARY_COUNTRIES.map(c => (
                <option key={c.code} value={c.code}>{c.label} ({c.currency})</option>
              ))}
            </select>
          </div>

          {/* CTA */}
          {stage === "idle" && (
            <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center" }} onClick={estimate}>
              <Icon name="writeai" size={15} /> Estimate My Market Value
            </button>
          )}

          {stage === "loading" && (
            <div style={{ textAlign:"center", padding:"28px 0" }}>
              <span className="spin" style={{ width:28, height:28, borderWidth:3, borderColor:"rgba(28,155,230,.2)", borderTopColor:"var(--brand-blue)", display:"inline-block" }} />
              <p style={{ marginTop:14, color:"var(--slate-500)", fontSize:13 }}>Fetching market data…</p>
            </div>
          )}

          {stage === "error" && (limitHit ? <ProUpgradeCard onClose={onClose} /> : (
            <div style={{ textAlign:"center" }}>
              <p style={{ color:"var(--danger)", marginBottom:12 }}>{errMsg}</p>
              <button className="btn btn-grad" onClick={estimate}>Retry</button>
            </div>
          ))}

          {stage === "done" && result && (
            <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
              {/* Main range display */}
              <div style={{ padding:"20px", background:"linear-gradient(135deg,rgba(28,155,230,.06),rgba(45,227,154,.06))", border:"1px solid rgba(28,155,230,.18)", borderRadius:14 }}>
                <div style={{ textAlign:"center", marginBottom:16 }}>
                  <div style={{ fontSize:32, fontWeight:800, color:"var(--navy)", letterSpacing:"-.02em" }}>{fmt(result.mid)}</div>
                  <div style={{ fontSize:13, color:"var(--slate-500)", marginTop:3 }}>Median annual salary · {selectedCountry?.label}</div>
                </div>

                {/* Range bar */}
                <div style={{ position:"relative", marginBottom:10 }}>
                  <div style={{ height:8, borderRadius:99, background:"var(--slate-100)", overflow:"hidden" }}>
                    <div style={{ height:"100%", background:"linear-gradient(90deg,#1C9BE6,#2de39a)", borderRadius:99, width:"100%" }} />
                  </div>
                  <div style={{ position:"absolute", top:14, left:"0%", fontSize:11, fontWeight:650, color:"var(--slate-500)" }}>{fmt(result.min)}</div>
                  <div style={{ position:"absolute", top:14, left:"50%", transform:"translateX(-50%)", fontSize:11, fontWeight:700, color:"var(--brand-blue)" }}>{fmt(result.mid)}</div>
                  <div style={{ position:"absolute", top:14, right:"0%", fontSize:11, fontWeight:650, color:"var(--slate-500)", textAlign:"right" }}>{fmt(result.max)}</div>
                </div>
                <div style={{ display:"flex", justifyContent:"space-between", marginTop:28, fontSize:11, color:"var(--slate-400)" }}>
                  <span>Entry / Low</span><span>Median</span><span>Senior / High</span>
                </div>
              </div>

              {/* Percentile range */}
              {result.percentile25 && result.percentile75 && (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8 }}>
                  {[["25th percentile", result.percentile25, "#6b7280"], ["75th percentile", result.percentile75, "var(--brand-blue)"]].map(([label, val, color]) => (
                    <div key={label} style={{ padding:"12px 14px", background:"var(--slate-50)", borderRadius:10, border:"1px solid var(--slate-100)" }}>
                      <div style={{ fontSize:17, fontWeight:750, color }}>{fmt(val)}</div>
                      <div style={{ fontSize:11, color:"var(--slate-400)", marginTop:3 }}>{label}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Insight */}
              {result.insight && (
                <div style={{ padding:"12px 14px", background:"rgba(28,155,230,.06)", borderRadius:10, border:"1px solid rgba(28,155,230,.14)", fontSize:13, color:"var(--slate-600)", lineHeight:1.55 }}>
                  <span style={{ fontWeight:700, color:"var(--brand-blue)" }}>Market insight: </span>{result.insight}
                </div>
              )}

              {/* Top paying cities */}
              {(result.topPayingCities||[]).length > 0 && (
                <div>
                  <div style={{ fontSize:12, fontWeight:700, color:"var(--slate-500)", textTransform:"uppercase", letterSpacing:".06em", marginBottom:8 }}>Top paying cities</div>
                  <div style={{ display:"flex", flexWrap:"wrap", gap:6 }}>
                    {result.topPayingCities.map((city, i) => (
                      <span key={i} style={{ fontSize:12.5, fontWeight:600, color:"var(--navy)", background:"var(--slate-100)", padding:"4px 11px", borderRadius:99 }}>{city}</span>
                    ))}
                  </div>
                </div>
              )}

              <div style={{ display:"flex", gap:8 }}>
                <button className="btn btn-ghost btn-sm" style={{ flex:1, justifyContent:"center" }} onClick={() => { setStage("idle"); setResult(null); }}>← Change country</button>
                <button className="btn btn-grad btn-sm" style={{ flex:1, justifyContent:"center" }} onClick={estimate}>↺ Recalculate</button>
              </div>

              <p style={{ fontSize:11, color:"var(--slate-400)", margin:0, textAlign:"center", lineHeight:1.5 }}>
                AI estimates based on market data. Actual salaries vary by employer, sector, and negotiation.
              </p>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
