﻿/* global React, Icon */
// AZOR live demo: URL input -> /api/analyze -> in-page presentation.

const { useState, useMemo } = React;

const STEPS = [
  "Pobieranie strony postepowania",
  "Analiza dokumentow i zmian",
  "Budowa raportu 8 sekcji",
  "Ocena ryzyk i decyzja",
  "Prezentacja wyniku"
];

function AzorDemo() {
  const [url, setUrl] = useState("");
  const [deepParse, setDeepParse] = useState(true);
  const [loading, setLoading] = useState(false);
  const [stepIdx, setStepIdx] = useState(-1);
  const [error, setError] = useState("");
  const [result, setResult] = useState(null);

  async function runAnalysis() {
    if (!url.trim()) return;
    setError("");
    setResult(null);
    setLoading(true);
    setStepIdx(0);

    const ticker = setInterval(() => {
      setStepIdx((prev) => (prev < STEPS.length - 1 ? prev + 1 : prev));
    }, 850);

    try {
      const res = await fetch("/api/analyze", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: url.trim(), deep_parse: deepParse })
      });
      const contentType = (res.headers.get("content-type") || "").toLowerCase();
      let data;
      if (contentType.includes("application/json")) {
        data = await res.json();
      } else {
        throw new Error("Nieprawidlowy format odpowiedzi z API.");
      }
      if (!res.ok || !data.success) {
        throw new Error(data.error || "Analiza nieudana.");
      }
      setResult(data);
      setStepIdx(STEPS.length - 1);
    } catch (e) {
      setError(e?.message || "Blad analizy.");
    } finally {
      clearInterval(ticker);
      setLoading(false);
    }
  }

  function reset() {
    setUrl("");
    setResult(null);
    setError("");
    setStepIdx(-1);
    setLoading(false);
  }

  const decisionClass = useMemo(() => {
    const d = result?.report_json?.go_no_go?.decision || "";
    if (d === "STARTUJEMY") return { bg: "var(--olive-600)", fg: "#fff" };
    if (d === "NIE STARTUJEMY") return { bg: "var(--crimson-700)", fg: "#fff" };
    return { bg: "var(--amber-500)", fg: "#1f1606" };
  }, [result]);

  return (
    <>
    <div style={{
      background: "var(--paper-2)",
      border: "1px solid var(--rule)",
      borderRadius: "var(--r-lg)",
      boxShadow: "var(--shadow-lift)",
      overflow: "hidden"
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "10px 16px",
        borderBottom: "1px solid var(--rule)",
        background: "linear-gradient(180deg, var(--paper-2) 0%, var(--paper-3) 100%)",
        fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)",
        letterSpacing: "0.06em", textTransform: "uppercase"
      }}>
        <span>azor.analyze</span>
        <span style={{ marginLeft: "auto" }}>{deepParse ? "deep pdf/zip mode" : "quick html mode"}</span>
      </div>

      {!result && (
        <div style={{ padding: "26px 26px 22px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>&gt; URL POSTEPOWANIA</div>
          <div style={{
            display: "grid",
            gridTemplateColumns: "1fr auto",
            gap: 8,
            border: "1px solid var(--rule-strong)",
            borderRadius: "var(--r-md)",
            background: "#fff",
            padding: 6,
            alignItems: "center"
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "0 8px" }}>
              <Icon name="link" size={18} />
              <input
                type="text"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && !loading && runAnalysis()}
                placeholder="https://biosg.ezamawiajacy.pl/.../details"
                style={{
                  flex: 1, border: "none", outline: "none", background: "transparent",
                  fontFamily: "var(--font-mono)", fontSize: 12, padding: "10px 0", color: "var(--ink)"
                }}
              />
            </div>
            <button
              onClick={runAnalysis}
              disabled={loading || !url.trim()}
              style={{
                background: loading || !url.trim() ? "var(--rule)" : "var(--copper-600)",
                color: loading || !url.trim() ? "var(--ink-3)" : "#fff",
                border: "none", padding: "11px 17px", borderRadius: "var(--r-sm)",
                fontWeight: 600, fontSize: 12, cursor: loading || !url.trim() ? "not-allowed" : "pointer",
                display: "inline-flex", alignItems: "center", gap: 8
              }}
            >
              {loading ? "Analizuje..." : "Przeanalizuj"}
              <Icon name="arrow-right" size={15} />
            </button>
          </div>

          <label style={{
            marginTop: 12,
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            fontSize: 12,
            color: "var(--ink-2)",
            cursor: "pointer"
          }}>
            <input type="checkbox" checked={deepParse} onChange={(e) => setDeepParse(e.target.checked)} />
            Pelna analiza PDF/ZIP (sekcje 5-8 z danymi technicznymi)
          </label>

          {loading && (
            <div style={{ marginTop: 16, display: "grid", gap: 6 }}>
              {STEPS.map((s, i) => {
                const done = i < stepIdx;
                const active = i === stepIdx;
                return (
                  <div key={s} style={{
                    border: active ? "1px solid var(--copper-100)" : "1px solid transparent",
                    background: active ? "var(--copper-50)" : "transparent",
                    borderRadius: "var(--r-sm)",
                    padding: "8px 10px",
                    fontSize: 12,
                    color: done || active ? "var(--ink)" : "var(--ink-3)"
                  }}>
                    {done ? "OK " : active ? "... " : "o "} {s}
                  </div>
                );
              })}
            </div>
          )}

          {error && (
            <div style={{
              marginTop: 12,
              border: "1px solid #e8b7b2",
              background: "#fff0ee",
              borderRadius: "var(--r-sm)",
              color: "#7d2e26",
              padding: "10px 12px",
              fontSize: 12
            }}>
              {error}
            </div>
          )}
        </div>
      )}

      {result && (
        <div style={{ padding: "20px 22px 16px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "flex-start" }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)" }}>
                {result.report_json?.basic_data?.proceeding_number || "brak numeru"}
              </div>
              <div style={{ fontSize: 18, color: "var(--navy-950)", fontWeight: 600, lineHeight: 1.15 }}>
                {result.report_json?.basic_data?.title || "Analiza przetargu"}
              </div>
              <div style={{ marginTop: 6, fontSize: 12, color: "var(--ink-2)" }}>
                Tryb: {result.report_json?.parser_mode === "deep_pdf" ? "Pelna analiza PDF/ZIP" : "Szybka analiza HTML"}
              </div>
            </div>
            <div style={{
              background: decisionClass.bg,
              color: decisionClass.fg,
              borderRadius: 999,
              padding: "6px 11px",
              fontFamily: "var(--font-mono)",
              fontSize: 10,
              letterSpacing: "0.04em"
            }}>
              {result.report_json?.go_no_go?.decision || "WARUNKOWO"}
            </div>
          </div>

          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <MetaCard k="Termin skladania" v={result.report_json?.basic_data?.submission_deadline || "brak"} />
            <MetaCard k="Rodzaj zamowienia" v={result.report_json?.basic_data?.tender_type || "brak"} />
            <MetaCard k="Szyfrowanie oferty" v={result.report_json?.basic_data?.offer_encryption || "brak"} />
            <MetaCard k="Confidence" v={result.report_json?.confidence || "medium"} />
          </div>

          <ReportPresentation report={result.report_json} />

          <div style={{ marginTop: 16, display: "flex", gap: 8, flexWrap: "wrap" }}>
            <button onClick={reset} style={miniBtnStyle}>Nowa analiza</button>
          </div>
        </div>
      )}
    </div>
    {result && <ReportWorkspace report={result.report_json} onClose={reset} />}
    </>
  );
}

function ReportWorkspace({ report, onClose }) {
  const meta = report?.basic_data || {};
  const decision = report?.go_no_go?.decision || "WARUNKOWO";
  const risks = report?.risk_register || [];
  const docs = report?.document_insights || [];
  const decisionTone = decision === "STARTUJEMY" ? "var(--olive-600)" : decision === "NIE STARTUJEMY" ? "var(--crimson-700)" : "var(--amber-500)";

  return (
    <div style={{
      position: "fixed",
      inset: 0,
      zIndex: 200,
      background: "var(--paper)",
      color: "var(--ink)",
      overflow: "auto"
    }}>
      <div style={{
        position: "sticky",
        top: 0,
        zIndex: 3,
        display: "flex",
        alignItems: "center",
        gap: 16,
        padding: "14px 28px",
        borderBottom: "1px solid var(--rule)",
        background: "rgba(246,241,233,0.96)",
        backdropFilter: "blur(10px)"
      }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 600, color: "var(--navy-950)" }}>AZOR</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)" }}>
          {report?.parser_mode === "deep_pdf" ? "PELNA ANALIZA PDF" : "SZYBKA ANALIZA HTML"}
        </div>
        <button onClick={onClose} style={{ ...miniBtnStyle, marginLeft: "auto" }}>Nowa analiza</button>
      </div>

      <main style={{ maxWidth: 1360, margin: "0 auto", padding: "28px 28px 56px" }}>
        <section style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) 320px", gap: 20 }} className="report-hero-grid">
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--copper-600)", marginBottom: 8 }}>
              {meta.proceeding_number || "BRAK NUMERU"}
            </div>
            <h1 style={{ fontFamily: "var(--font-display)", fontSize: 34, lineHeight: 1.08, margin: 0, color: "var(--navy-950)", fontWeight: 600 }}>
              {meta.title || "Analiza przetargu"}
            </h1>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", gap: 10, marginTop: 18 }} className="report-kpis">
              <Kpi label="Rodzaj" value={meta.tender_type || "BRAK"} />
              <Kpi label="Termin" value={meta.submission_deadline || "BRAK"} />
              <Kpi label="Otwarcie" value={meta.opening_datetime || "BRAK"} />
              <Kpi label="Dokumenty" value={`${(report.documents || []).length + (report.changes_qa || []).length}`} />
            </div>
          </div>

          <aside style={{
            background: "#fff",
            border: "1px solid var(--rule)",
            borderRadius: 8,
            padding: 16,
            boxShadow: "var(--shadow-card)"
          }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)", marginBottom: 8 }}>DECYZJA</div>
            <div style={{ display: "inline-flex", background: decisionTone, color: decision === "WARUNKOWO" ? "#1f1606" : "#fff", borderRadius: 6, padding: "8px 10px", fontWeight: 700, fontSize: 13 }}>
              {decision}
            </div>
            <div style={{ marginTop: 12, display: "grid", gap: 7 }}>
              {(report?.go_no_go?.decision_rationale || []).map((x, i) => <SmallLine key={i}>{x}</SmallLine>)}
            </div>
          </aside>
        </section>

        <section style={{ marginTop: 22, display: "grid", gridTemplateColumns: "320px minmax(0, 1fr)", gap: 20 }} className="report-main-grid">
          <aside style={{ display: "grid", gap: 12, alignSelf: "start", position: "sticky", top: 74 }}>
            <Panel title="Dokumenty">
              {(docs.length ? docs : (report.documents || [])).slice(0, 12).map((d, i) => (
                <DocLine key={i} doc={d} />
              ))}
            </Panel>
            <Panel title="Ryzyka">
              {risks.length ? risks.map((r, i) => <SmallLine key={i}>{`[${String(r.level || "").toUpperCase()}] ${r.area}: ${r.note}`}</SmallLine>) : <SmallLine>Brak ryzyk automatycznych.</SmallLine>}
            </Panel>
          </aside>

          <ReportPresentation report={report} />
        </section>
      </main>

      <style>{`
        @media (max-width: 980px) {
          .report-hero-grid, .report-main-grid { grid-template-columns: 1fr !important; }
          .report-kpis { grid-template-columns: 1fr 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function Kpi({ label, value }) {
  return (
    <div style={{ background: "#fff", border: "1px solid var(--rule)", borderRadius: 8, padding: 12 }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-3)", marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 12, lineHeight: 1.3, color: "var(--ink)", fontWeight: 600 }}>{value}</div>
    </div>
  );
}

function Panel({ title, children }) {
  return (
    <div style={{ background: "#fff", border: "1px solid var(--rule)", borderRadius: 8, padding: 14 }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--copper-600)", marginBottom: 10 }}>{title}</div>
      <div style={{ display: "grid", gap: 8 }}>{children}</div>
    </div>
  );
}

function SmallLine({ children }) {
  return <div style={{ fontSize: 12, lineHeight: 1.45, color: "var(--ink-2)" }}>{children}</div>;
}

function DocLine({ doc }) {
  const label = doc.kind || doc.doc_type || "dokument";
  const parsed = doc.parsed ? "OK" : "";
  return (
    <div style={{ borderTop: "1px solid var(--rule)", paddingTop: 8 }}>
      <div style={{ fontSize: 12, lineHeight: 1.3, color: "var(--ink)", fontWeight: 600 }}>{doc.name}</div>
      <div style={{ marginTop: 4, fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-3)" }}>
        {label} {doc.size ? `| ${doc.size}` : ""} {parsed ? `| parsed ${parsed}` : ""}
      </div>
    </div>
  );
}

function ReportPresentation({ report }) {
  const meta = report?.basic_data || {};
  const buyer = report?.authority || {};
  const req = report?.experience_requirement || {};
  const scope = report?.scope_of_work || {};
  const risk = report?.risk_register || [];

  return (
    <div style={{ marginTop: 16, display: "grid", gap: 12 }}>
      <SectionCard code="01 META" title="Podstawowe dane" lines={[
        `Nr postepowania: ${meta.proceeding_number || "BRAK"}`,
        `Tryb: ${meta.procedure_mode || "BRAK"}`,
        `CPV: ${meta.cpv || "BRAK"}`,
        `Wadium: ${meta.bid_bond || "BRAK"}`
      ]} />

      <SectionCard code="02 BUYER" title="Zamawiajacy" lines={[
        `Nazwa: ${buyer.full_name || "BRAK"}`,
        `Kontakt: ${buyer.contact_person || "BRAK"}`,
        `Telefon: ${buyer.phone || "BRAK"}`,
        `Email: ${buyer.email || "BRAK"}`
      ]} />

      <SectionCard code="03 DOCS" title="Dokumenty" lines={[
        `PDF odczytane: ${(report.deep_parse?.parsed_documents || []).length}`,
        `ZIP rozpoznane: ${report.deep_parse?.zip_manifests_count || 0}`,
        ...(report.zip_manifests || []).slice(0, 2).map((z) => `ZIP: ${z.name} | pliki: ${z.files_count}`),
        ...(report.documents || []).slice(0, 8).map((d) => `${d.name} | ${d.size || "-"}`)
      ]} />

      <SectionCard code="04 DELTA" title="Zmiany i Q&A" lines={(report.changes_qa || []).slice(0, 8).map((d) => `${d.date || "-"} | ${d.name}`)} />

      <SectionCard code="05 REQ" title="Doswiadczenie" lines={[
        req.current_wording || "Wymaga odczytu SWZ/zmian.",
        `Prog brutto: ${req.threshold_pln_gross ? req.threshold_pln_gross + " PLN" : "BRAK"}`,
        `Okres: ${req.lookback_period_years ? req.lookback_period_years + " lat" : "BRAK"}`,
        req.practical_implication || "Brak implikacji z parsera."
      ]} />

      <SectionCard code="06 SCOPE" title="Zakres robot" lines={[
        ...(scope.building || []).map((x) => `Budowlana: ${x}`),
        ...(scope.sanitary || []).map((x) => `Sanitarna: ${x}`),
        ...(scope.electrical || []).map((x) => `Elektryczna: ${x}`),
        ...(scope.terrain || []).map((x) => `Teren: ${x}`),
        ...((report.zip_manifests || []).flatMap((z) => (z.files || []).slice(0, 5).map((f) => `${f.kind}: ${f.name}`))).slice(0, 10)
      ]} />

      <SectionCard code="07 SYS" title="Systemy i instalacje" lines={(report.electronic_systems || []).length ? report.electronic_systems : ["Brak potwierdzonych danych systemowych."]} />

      <SectionCard code="08 RISK" title="Ryzyka" lines={[
        ...risk.map((r) => `[${String(r.level || "").toUpperCase()}] ${r.area}: ${r.note}`),
        ...(report.missing_info || []).slice(0, 5).map((m) => `Brak: ${m.field} (${m.impact_on_bid})`)
      ]} />

      <SectionCard code="DECYZJA" title="Rekomendacja" lines={[
        `Decyzja: ${report?.go_no_go?.decision || "WARUNKOWO"}`,
        ...((report?.go_no_go?.decision_rationale || [])),
        ...((report?.go_no_go?.conditions_to_start || []).map((x) => `Warunek: ${x}`))
      ]} />
    </div>
  );
}

function SectionCard({ code, title, lines }) {
  const list = (lines || []).filter(Boolean);
  return (
    <div style={{
      background: "#fff",
      border: "1px solid var(--rule)",
      borderRadius: "var(--r-sm)",
      padding: 12
    }}>
      <div style={{ display: "flex", gap: 8, alignItems: "baseline", marginBottom: 8 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--copper-600)" }}>{code}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: "var(--navy-950)" }}>{title}</span>
      </div>
      <div style={{ display: "grid", gap: 5 }}>
        {list.length === 0 ? <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Brak danych</span> : null}
        {list.map((line, i) => (
          <div key={i} style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.45 }}>
            - {line}
          </div>
        ))}
      </div>
    </div>
  );
}

function MetaCard({ k, v }) {
  return (
    <div style={{
      background: "#fff",
      border: "1px solid var(--rule)",
      borderRadius: "var(--r-sm)",
      padding: "9px 10px"
    }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-3)", marginBottom: 5 }}>{k}</div>
      <div style={{ fontSize: 12, color: "var(--ink)", fontWeight: 500 }}>{v}</div>
    </div>
  );
}

const miniBtnStyle = {
  textDecoration: "none",
  border: "1px solid var(--rule-strong)",
  background: "#fff",
  color: "var(--ink-2)",
  borderRadius: "var(--r-sm)",
  padding: "7px 11px",
  fontFamily: "var(--font-mono)",
  fontSize: 10,
  letterSpacing: "0.04em",
  cursor: "pointer"
};

window.AzorDemo = AzorDemo;
