// Woodbury Operator — Reports & Analytics. Registers window.ReportsScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, StatCard, IconTile, Modal, Select, Eyebrow, ProgressBar } = NS;

  function BarChart() {
    const bars = [
      { label: "Lashibi TH", v: 56 }, { label: "Lashibi Exec", v: 88 }, { label: "Mirage", v: 92 },
      { label: "Onehive", v: 78 }, { label: "Hamlet", v: 100 }, { label: "Cant. City", v: 90 },
    ];
    return (
      <div style={{ display: "flex", alignItems: "flex-end", gap: 18, height: 190, padding: "0 4px" }}>
        {bars.map((b) => (
          <div key={b.label} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: "var(--text-heading)" }}>{b.v}%</span>
            <div style={{ width: "100%", height: b.v * 1.5, borderRadius: "8px 8px 0 0", background: b.v >= 95 ? "var(--success)" : "var(--brand)" }} />
            <span style={{ fontSize: 11, color: "var(--text-muted)", textAlign: "center" }}>{b.label}</span>
          </div>
        ))}
      </div>
    );
  }

  // Simple SVG line chart — occupancy trend over 6 months.
  function TrendChart() {
    const pts = [86, 88, 87, 90, 91, 92];
    const labels = ["Mar", "Apr", "May", "Jun", "Jul", "Aug"];
    const W = 320, H = 150, pad = 10;
    const min = 82, max = 96;
    const x = (i) => pad + (i * (W - pad * 2)) / (pts.length - 1);
    const y = (v) => H - pad - ((v - min) / (max - min)) * (H - pad * 2);
    const d = pts.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
    const area = d + ` L ${x(pts.length - 1)} ${H - pad} L ${x(0)} ${H - pad} Z`;
    return (
      <div>
        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: 170 }} preserveAspectRatio="none">
          <path d={area} fill="rgba(94,59,26,0.08)" />
          <path d={d} fill="none" stroke="var(--brand)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
          {pts.map((v, i) => <circle key={i} cx={x(i)} cy={y(v)} r="3.5" fill="var(--brand)" />)}
        </svg>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "0 6px", marginTop: 4 }}>
          {labels.map((l) => <span key={l} style={{ fontSize: 11, color: "var(--text-muted)" }}>{l}</span>)}
        </div>
      </div>
    );
  }

  // Report catalog grouped by category — the reports admins actually run.
  const CATALOG = [
    { group: "Occupancy & Leasing", tone: "brand", items: [
      { name: "Occupancy & Vacancy Summary", desc: "Occupied vs vacant units per estate, with trend.", icon: "building-2", scope: "both" },
      { name: "Lease Expiry & Renewal Pipeline", desc: "Leases ending in 30/60/90 days and renewal status.", icon: "calendar-clock", scope: "both" },
      { name: "Tenant Turnover & Retention", desc: "Move-ins, move-outs, and retention rate by site.", icon: "repeat", scope: "both" },
    ]},
    { group: "Maintenance & Facilities", tone: "accent", items: [
      { name: "Maintenance Performance", desc: "Tickets opened/closed, avg resolution, by category.", icon: "wrench", scope: "both" },
      { name: "Vendor SLA & Performance", desc: "Response time, jobs completed, and rating by vendor.", icon: "hard-hat", scope: "both" },
      { name: "Recurring Issues Analysis", desc: "Most frequent fault types by unit and estate.", icon: "chart-column", scope: "super" },
    ]},
    { group: "Screening & Compliance", tone: "success", items: [
      { name: "Applications Funnel", desc: "Applicants → verified → approved, with turnaround.", icon: "shield-check", scope: "both" },
      { name: "Inspections & Compliance", desc: "Inspections done/overdue and certificate expiries.", icon: "clipboard-check", scope: "both" },
      { name: "Communications Log", desc: "Broadcasts and resident notices sent, by site.", icon: "megaphone", scope: "both" },
    ]},
    { group: "Portfolio Oversight", tone: "sunken", items: [
      { name: "Cross-Site Portfolio Scorecard", desc: "All estates compared on occupancy, tickets, SLA.", icon: "layout-grid", scope: "super" },
      { name: "Staff Activity & Audit Summary", desc: "Actions per user and role across the portfolio.", icon: "scroll-text", scope: "super" },
    ]},
  ];

  const RECENT = [
    { name: "Q1 2026 Occupancy Summary", meta: "Generated 01 Apr · PDF", icon: "trending-up", tone: "brand" },
    { name: "Maintenance Performance — Accra", meta: "Generated 28 Mar · PDF", icon: "wrench", tone: "accent" },
    { name: "Lease Expiry Forecast", meta: "Generated 02 Mar · XLSX", icon: "calendar-clock", tone: "success" },
  ];

  function ReportsScreen() {
    const isSuper = (window.WB_ACTIVE_ROLE || "super") === "super";
    const [period, setPeriod] = React.useState("This Quarter");
    const [pick, setPick] = React.useState(false);
    const [gen, setGen] = React.useState(null); // null | {name} preselected

    const catalog = CATALOG.map((c) => ({ ...c, items: c.items.filter((it) => it.scope === "both" || (it.scope === "super" && isSuper)) })).filter((c) => c.items.length);
    const allTypes = catalog.flatMap((c) => c.items.map((it) => it.name));

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Analytics" title="Reports & Analytics"
          sub={isSuper ? "Portfolio-wide performance across every estate in Ghana." : "Operational analytics for your assigned site."}
          actions={<React.Fragment>
            <Button variant="secondary" icon="calendar" onClick={() => setPick(true)}>{period}</Button>
            <Button variant="primary" icon="plus" onClick={() => setGen({ name: allTypes[0] })}>Generate Report</Button>
          </React.Fragment>} />

        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={() => window.WBNavigate && window.WBNavigate("Properties")} label="Portfolio Occupancy" value="92%" icon="building-2" iconTone="success" emphasis="success" delta="+1.2%" />
          <StatCard onClick={() => window.WBNavigate && window.WBNavigate("Maintenance")} label="Avg. Resolution" value="1.4d" icon="clock" iconTone="accent" />
          <StatCard onClick={() => window.WBNavigate && window.WBNavigate("Leases")} label="Renewals Due" value="5" icon="calendar-clock" iconTone="brand" />
          <StatCard label="Retention Rate" value="95.9%" icon="repeat" iconTone="success" emphasis="success" />
        </div>

        {/* Charts */}
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 24, alignItems: "start" }}>
          <Card>
            <CardHeader title={"Occupancy by Estate · " + period} action={<Badge tone="success" dot>Live</Badge>} />
            <div style={{ padding: 28 }}><BarChart /></div>
          </Card>
          <Card>
            <CardHeader title="Occupancy Trend" action={<Badge tone="success">+6% YTD</Badge>} />
            <div style={{ padding: "24px 24px 18px" }}><TrendChart /></div>
          </Card>
        </div>

        {/* Maintenance breakdown */}
        <Card>
          <CardHeader title="Maintenance by Category · This Quarter" />
          <div style={{ padding: "22px 28px", display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: "18px 40px" }}>
            {[["Plumbing", 34, "brand"], ["HVAC / Cooling", 28, "accent"], ["Electrical", 19, "success"], ["Structural / Roofing", 12, "sunken"], ["Access & Gates", 5, "brand"], ["Appliances", 2, "accent"]].map(([label, v, tone]) => (
              <div key={label}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 6 }}><span style={{ color: "var(--text-heading)", fontWeight: 600 }}>{label}</span><span style={{ color: "var(--text-muted)" }}>{v}%</span></div>
                <ProgressBar value={v} tone={tone} />
              </div>
            ))}
          </div>
        </Card>

        {/* Report library */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <h2 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 24, color: "var(--text-heading)" }}>Report Library</h2>
            <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{allTypes.length} report types</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            {catalog.map((cat) => (
              <div key={cat.group}>
                <Eyebrow>{cat.group}</Eyebrow>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginTop: 12 }}>
                  {cat.items.map((it) => (
                    <Card key={it.name} style={{ padding: 20, display: "flex", flexDirection: "column", gap: 12 }}>
                      <IconTile icon={it.icon} tone={cat.tone} size={42} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{it.name}</div>
                        <p style={{ margin: "4px 0 0", fontSize: 13, lineHeight: 1.5, color: "var(--text-body)" }}>{it.desc}</p>
                      </div>
                      <div style={{ display: "flex", gap: 8 }}>
                        <Button variant="primary" size="sm" icon="file-chart-column" onClick={() => setGen({ name: it.name })}>Generate</Button>
                        <Button variant="ghost" size="sm" icon="eye" onClick={() => window.WBToast("Previewing " + it.name)}>Preview</Button>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent */}
        <Card>
          <CardHeader title="Recently Generated" />
          {RECENT.map((r, i) => (
            <div key={r.name} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <IconTile icon={r.icon} tone={r.tone} size={40} />
              <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{r.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{r.meta}</div></div>
              <Button variant="ghost" size="sm" icon="download" onClick={() => window.WBToast("Downloading " + r.name)} />
            </div>
          ))}
        </Card>

        {/* Period picker */}
        <Modal open={pick} onClose={() => setPick(false)} icon="calendar" title="Reporting Period" subtitle="Choose the time range for analytics." width={420}>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {["This Month", "This Quarter", "Year to Date", "Last 12 Months"].map((p) => (
              <button key={p} onClick={() => { setPeriod(p); setPick(false); window.WBToast("Showing: " + p); }} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", border: "1px solid var(--border)", background: p === period ? "var(--brand-tint)" : "var(--surface)", cursor: "pointer", padding: "13px 16px", borderRadius: "var(--radius-md)", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--text-heading)" }}>
                {p}{p === period && <span className="wb-ico" style={{ width: 16, height: 16, color: "var(--brand)" }}><i data-lucide="check"></i></span>}
              </button>
            ))}
          </div>
        </Modal>

        {/* Generate report */}
        <Modal open={!!gen} onClose={() => setGen(null)} icon="file-chart-column" title="Generate Report" subtitle="Build a new analytics export."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setGen(null)}>Cancel</Button><Button variant="primary" icon="download" onClick={() => { const n = gen.name; setGen(null); window.WBToast(n + " generated & downloaded"); }}>Generate</Button></React.Fragment>}>
          {gen && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Select label="Report type" defaultValue={gen.name} options={allTypes} onChange={(e) => setGen({ name: e.target.value })} />
              <Select label="Scope" options={isSuper ? ["All Ghana Locations", ...window.WB_SITES] : [window.WB_SITES[0]]} />
              <div style={{ display: "flex", gap: 14 }}>
                <Select label="Period" defaultValue={period} options={["This Month", "This Quarter", "Year to Date", "Last 12 Months"]} containerStyle={{ flex: 1 }} />
                <Select label="Format" options={["PDF", "XLSX", "CSV"]} containerStyle={{ flex: 1 }} />
              </div>
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.ReportsScreen = ReportsScreen;
})();
