// app/mines/[projectId]/page.js
// Per-project overview shell — Server Component.
// Calls getPortfolioEntryDetail() from lib/mines/portfolio.js directly (no
// fetch round-trip needed from a Server Component).
// Next.js 15: params is a Promise — must be awaited.

import Link from "next/link";
import { getPortfolioEntryDetail } from "../../../lib/mines/portfolio.js";
import { getProjectDataQuality } from "../../../lib/mines/data-quality.js";
import ImportPanel from "./import-panel.jsx";
import DiligenceButton from "./diligence-button.jsx";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

// ---------------------------------------------------------------------------
// Metadata
// ---------------------------------------------------------------------------

export async function generateMetadata({ params }) {
  const { projectId } = await params;
  try {
    const detail = getPortfolioEntryDetail(projectId);
    if (detail?.entry?.name) {
      return { title: `${detail.entry.name} — Mines` };
    }
  } catch {
    // fall through
  }
  return { title: "Project — Mines" };
}

// ---------------------------------------------------------------------------
// Inline SVG icons
// ---------------------------------------------------------------------------

function IconArrowLeft() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M10 12L6 8l4-4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconDrill() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M12 2v16M8 18l4 4 4-4" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="12" cy="8" r="3" />
    </svg>
  );
}

function IconDoc() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
      <polyline points="14 2 14 8 20 8" />
    </svg>
  );
}

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

/** A single metadata cell used in the info grid. */
function InfoCell({ label, value, mono = false }) {
  return (
    <div
      style={{
        padding: "14px 16px",
        border: "1px solid rgba(17,19,24,.07)",
        borderRadius: 12,
        background: "#fff",
        display: "flex",
        flexDirection: "column",
        gap: 6,
      }}
    >
      <span
        style={{
          fontSize: 10,
          fontWeight: 850,
          letterSpacing: ".12em",
          textTransform: "uppercase",
          color: "#8a8f99",
        }}
      >
        {label}
      </span>
      <span
        style={{
          fontSize: 13.5,
          fontWeight: 600,
          color: value ? "#111318" : "#9aa0aa",
          fontFamily: mono ? "ui-monospace, SFMono-Regular, Menlo, monospace" : undefined,
          fontStyle: value ? "normal" : "italic",
          letterSpacing: mono ? "-.01em" : "-.005em",
        }}
      >
        {value ?? "—"}
      </span>
    </div>
  );
}

/** Count stat used in the "Data" summary strip. */
function CountStat({ label, value, icon: Icon }) {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 6,
        padding: "14px 18px",
        borderRight: "1px solid rgba(17,19,24,.07)",
        minWidth: 0,
        flex: 1,
      }}
    >
      <b
        style={{
          fontSize: 30,
          fontWeight: 300,
          letterSpacing: "-.05em",
          lineHeight: 1,
          color: "#111318",
          fontFeatureSettings: '"tnum","lnum"',
        }}
      >
        {value ?? 0}
      </b>
      <span style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 10.5, fontWeight: 650, letterSpacing: ".14em", textTransform: "uppercase", color: "#8a8f99" }}>
        {Icon && <Icon />}
        {label}
      </span>
    </div>
  );
}

/** Tab bar. Active tabs are links (?tab=); future-phase tabs are disabled. */
function TabBar({ activeTab, entryId }) {
  const tabs = [
    { id: "overview", label: "Overview", phase: null, active: true },
    { id: "data",     label: "Data",     phase: null, active: true },
    { id: "valuation", label: "Valuation", phase: "P3", active: false },
    { id: "spatial",  label: "Spatial",  phase: "P5",  active: false },
  ];

  return (
    <div
      role="tablist"
      aria-label="Project sections"
      style={{
        display: "flex",
        alignItems: "flex-end",
        gap: 24,
        borderBottom: "1px solid rgba(17,19,24,.10)",
        marginBottom: 24,
      }}
    >
      {tabs.map((tab) => {
        const isCurrent = tab.id === (activeTab || "overview");
        const inner = (
          <>
            {tab.label}
            {tab.phase && (
              <span
                style={{
                  fontSize: 9.5,
                  fontWeight: 750,
                  letterSpacing: ".10em",
                  textTransform: "uppercase",
                  color: "#b0b6bf",
                  fontFamily: "ui-monospace, monospace",
                }}
                title={`Coming in ${tab.phase}`}
              >
                {tab.phase}
              </span>
            )}
            {isCurrent && (
              <span
                aria-hidden="true"
                style={{
                  position: "absolute",
                  left: 0,
                  right: 0,
                  bottom: -1,
                  height: 2,
                  background: "var(--accent-500, #c2452a)",
                  borderRadius: 2,
                }}
              />
            )}
          </>
        );

        const baseStyle = {
          position: "relative",
          paddingBottom: 14,
          display: "inline-flex",
          alignItems: "baseline",
          gap: 7,
          cursor: tab.active ? "pointer" : "not-allowed",
          color: isCurrent ? "#111318" : tab.active ? "#68707b" : "#b0b6bf",
          fontSize: 14,
          fontWeight: isCurrent ? 650 : 500,
          letterSpacing: "-.01em",
          userSelect: "none",
          textDecoration: "none",
        };

        if (tab.active && !isCurrent) {
          const href = tab.id === "overview"
            ? `/mines/${entryId}`
            : `/mines/${entryId}?tab=${tab.id}`;
          return (
            <Link key={tab.id} href={href} role="tab" aria-selected={false} style={baseStyle}>
              {inner}
            </Link>
          );
        }

        return (
          <div
            key={tab.id}
            role="tab"
            aria-selected={isCurrent}
            aria-disabled={!tab.active}
            style={baseStyle}
          >
            {inner}
          </div>
        );
      })}
    </div>
  );
}

/** Server-rendered Data tab: per-category completeness + import panel. */
function DataTab({ entry, project }) {
  if (!project) {
    return (
      <section aria-label="Data ingestion">
        <div className="admin-empty" style={{ maxWidth: 520 }}>
          <b>No linked project</b>
          <p>
            This portfolio entry isn&rsquo;t linked to a project workspace yet. Create or link a
            project before importing data (documents, assays, drill holes).
          </p>
        </div>
      </section>
    );
  }

  let dq = null;
  try {
    dq = getProjectDataQuality(project.id);
  } catch {
    dq = null;
  }

  const score = dq?.completeness_score ?? 0;
  const scorePct = Math.round(score * 100);

  return (
    <section aria-label="Data ingestion">
      <ImportPanel minesProjectId={project.id} initialProgress={dq?.progress || null} />

      {/* Completeness summary */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginBottom: 18 }}>
        <DataStat label="Completeness" value={`${scorePct}%`} />
        <DataStat label="Documents" value={dq?.totals?.documents ?? 0} />
        <DataStat label="Text chunks" value={dq?.totals?.chunks ?? 0} />
        <DataStat label="Spatial assets" value={dq?.spatial_assets_count ?? 0} hint="Mapped in Spatial (P5)" />
      </div>

      {/* Per-category table */}
      <div
        style={{
          border: "1px solid rgba(17,19,24,.08)",
          borderRadius: 16,
          background: "#fff",
          overflow: "hidden",
        }}
      >
        <div style={{ padding: "12px 16px", borderBottom: "1px solid rgba(17,19,24,.07)" }}>
          <span style={{ fontSize: 13, fontWeight: 750, color: "#111318" }}>Completeness by category</span>
        </div>

        {!dq || dq.categories.length === 0 ? (
          <div className="admin-empty" style={{ margin: 0, borderRadius: 0, border: 0, background: "transparent" }}>
            <b>No documents imported yet</b>
            <p>Use &ldquo;Run import&rdquo; above to ingest a data directory for this project.</p>
          </div>
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <thead>
                <tr style={{ textAlign: "left", color: "#8a8f99" }}>
                  <Th>Category</Th>
                  <Th align="right">Docs</Th>
                  <Th align="right">Chunks</Th>
                  <Th>Status breakdown</Th>
                </tr>
              </thead>
              <tbody>
                {dq.categories.map((c) => (
                  <tr key={c.document_category} style={{ borderTop: "1px solid rgba(17,19,24,.06)" }}>
                    <Td mono>{c.document_category}</Td>
                    <Td align="right">{c.document_count}</Td>
                    <Td align="right">{c.chunk_count}</Td>
                    <Td>
                      {Object.entries(c.status_breakdown)
                        .map(([k, v]) => `${k}: ${v}`)
                        .join(" · ") || "—"}
                    </Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </section>
  );
}

function DataStat({ label, value, hint }) {
  return (
    <div
      style={{
        flex: "1 1 140px",
        minWidth: 120,
        padding: "12px 16px",
        border: "1px solid rgba(17,19,24,.07)",
        borderRadius: 12,
        background: "#fff",
      }}
    >
      <b style={{ fontSize: 26, fontWeight: 300, letterSpacing: "-.04em", color: "#111318", display: "block" }}>
        {value}
      </b>
      <span style={{ fontSize: 10, fontWeight: 750, letterSpacing: ".12em", textTransform: "uppercase", color: "#8a8f99" }}>
        {label}
      </span>
      {hint && <span style={{ display: "block", marginTop: 3, fontSize: 10.5, color: "#b0b6bf" }}>{hint}</span>}
    </div>
  );
}

function Th({ children, align = "left" }) {
  return (
    <th style={{ padding: "10px 16px", textAlign: align, fontSize: 10, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase" }}>
      {children}
    </th>
  );
}

function Td({ children, align = "left", mono = false }) {
  return (
    <td
      style={{
        padding: "9px 16px",
        textAlign: align,
        color: "#313740",
        fontFamily: mono ? "ui-monospace, SFMono-Regular, Menlo, monospace" : undefined,
        fontSize: mono ? 12 : 12.5,
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </td>
  );
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

export default async function ProjectOverviewPage({ params, searchParams }) {
  const { projectId } = await params;
  const sp = searchParams ? await searchParams : {};
  const activeTab = sp?.tab === "data" ? "data" : "overview";

  let detail = null;
  try {
    detail = getPortfolioEntryDetail(projectId);
  } catch {
    // Treat any error as not-found; the backend module may not exist yet during
    // parallel development. The not-found state below handles the UI.
  }

  // ── Not-found state ──
  if (!detail) {
    return (
      <main className="admin-shell">
        <header className="admin-header" style={{ marginBottom: 28 }}>
          <div>
            <span className="admin-kicker">Mines · Portfolio</span>
            <h1>Project not found</h1>
          </div>
        </header>

        <div className="admin-empty" style={{ maxWidth: 480 }}>
          <b>No entry for &ldquo;{projectId}&rdquo;</b>
          <p>This portfolio entry or project does not exist. It may have been removed, or the ID is incorrect.</p>
          <Link href="/mines" className="admin-link">
            <IconArrowLeft />
            Back to portfolio
          </Link>
        </div>
      </main>
    );
  }

  const { entry, project, counts } = detail;

  // ── Full overview ──
  const hasProject = !!project;
  const hasData = counts && (
    (counts.documents ?? 0) > 0 ||
    (counts.assays ?? 0) > 0 ||
    (counts.drill_holes ?? 0) > 0
  );

  return (
    <main className="admin-shell">
      {/* ── Page header ── */}
      <div style={{ marginBottom: 4 }}>
        <Link
          href="/mines"
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 5,
            fontSize: 11.5,
            fontWeight: 650,
            color: "#68707b",
            textDecoration: "none",
            letterSpacing: ".01em",
            marginBottom: 16,
          }}
        >
          <IconArrowLeft />
          Portfolio
        </Link>
      </div>

      <header className="admin-header" style={{ marginBottom: 24, alignItems: "flex-start" }}>
        <div>
          <span className="admin-kicker">
            Mines · {entry.commodity || "Mineral project"}
          </span>
          <h1 style={{ marginBottom: 0 }}>{entry.name}</h1>
          {entry.owner && (
            <p style={{ margin: "10px 0 0", fontSize: 14, color: "#68707b" }}>
              {entry.owner}
            </p>
          )}
        </div>

        {/* Completeness badge + diligence trigger */}
        <div className="admin-header-actions" style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 12 }}>
          {entry.data_completeness != null && (
            entry.data_completeness >= 0.8 ? (
              <span className="admin-pill ready">Full data</span>
            ) : entry.data_completeness >= 0.4 ? (
              <span className="admin-pill warn">Partial data</span>
            ) : (
              <span className="admin-pill danger">Low data</span>
            )
          )}
          {hasProject && <DiligenceButton minesProjectId={project.id} />}
        </div>
      </header>

      {/* ── Tab bar ── */}
      <TabBar activeTab={activeTab} entryId={projectId} />

      {activeTab === "data" ? (
        <DataTab entry={entry} project={project} />
      ) : (
        <>
      {/* ── Metadata grid ── */}
      <section aria-label="Project details">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))",
            gap: 10,
            marginBottom: 20,
          }}
        >
          <InfoCell label="Commodity"    value={entry.commodity} />
          <InfoCell label="Deposit type" value={entry.deposit_type} />
          <InfoCell
            label="Asset stage"
            value={hasProject ? (project.asset_stage ?? null) : null}
          />
          <InfoCell
            label="Country"
            value={hasProject ? (project.country ?? null) : null}
          />
          <InfoCell
            label="State / Province"
            value={hasProject ? (project.state_province ?? null) : null}
          />
          <InfoCell
            label="Has drilling"
            value={entry.has_drilling ? "Yes" : "No"}
          />
          <InfoCell
            label="Technical report"
            value={hasProject
              ? (project.has_technical_report ? "Yes" : "No")
              : null}
          />
        </div>

        {/* Deal terms */}
        {entry.deal_terms && (
          <div
            style={{
              padding: "14px 16px",
              border: "1px solid rgba(17,19,24,.07)",
              borderRadius: 12,
              background: "#fff",
              marginBottom: 10,
            }}
          >
            <span
              style={{
                display: "block",
                fontSize: 10,
                fontWeight: 850,
                letterSpacing: ".12em",
                textTransform: "uppercase",
                color: "#8a8f99",
                marginBottom: 8,
              }}
            >
              Deal terms
            </span>
            <p style={{ margin: 0, fontSize: 13.5, color: "#313740", lineHeight: 1.6 }}>
              {entry.deal_terms}
            </p>
          </div>
        )}

        {/* Available information */}
        {entry.available_information && (
          <div
            style={{
              padding: "14px 16px",
              border: "1px solid rgba(17,19,24,.07)",
              borderRadius: 12,
              background: "#fff",
              marginBottom: 10,
            }}
          >
            <span
              style={{
                display: "block",
                fontSize: 10,
                fontWeight: 850,
                letterSpacing: ".12em",
                textTransform: "uppercase",
                color: "#8a8f99",
                marginBottom: 8,
              }}
            >
              Available information
            </span>
            <p style={{ margin: 0, fontSize: 13.5, color: "#313740", lineHeight: 1.6 }}>
              {entry.available_information}
            </p>
          </div>
        )}

        {/* Notes */}
        {entry.notes && (
          <div
            style={{
              padding: "14px 16px",
              border: "1px solid rgba(17,19,24,.07)",
              borderRadius: 12,
              background: "#fff",
              marginBottom: 10,
            }}
          >
            <span
              style={{
                display: "block",
                fontSize: 10,
                fontWeight: 850,
                letterSpacing: ".12em",
                textTransform: "uppercase",
                color: "#8a8f99",
                marginBottom: 8,
              }}
            >
              Notes
            </span>
            <p style={{ margin: 0, fontSize: 13.5, color: "#555d68", lineHeight: 1.65, fontStyle: "italic" }}>
              {entry.notes}
            </p>
          </div>
        )}
      </section>

      {/* ── Data summary strip ── */}
      <section aria-label="Ingested data summary" style={{ marginTop: 24 }}>
        <div
          style={{
            border: "1px solid rgba(17,19,24,.08)",
            borderRadius: 16,
            background: "rgba(255,255,255,.78)",
            overflow: "hidden",
            boxShadow: "0 10px 30px rgba(17,19,24,.07)",
          }}
        >
          <div
            style={{
              padding: "12px 16px",
              borderBottom: "1px solid rgba(17,19,24,.07)",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <span style={{ fontSize: 13, fontWeight: 750, letterSpacing: "-.01em", color: "#111318" }}>
              Ingested data
            </span>
            {counts?.last_import_at && (
              <small style={{ fontSize: 11.5, color: "#8a8f99" }}>
                Last import:{" "}
                {new Date(counts.last_import_at).toLocaleDateString("en-US", {
                  year: "numeric",
                  month: "short",
                  day: "numeric",
                })}
              </small>
            )}
          </div>

          {!hasData && !hasProject ? (
            /* No linked project and no counts */
            <div
              className="admin-empty"
              style={{ margin: 0, borderRadius: 0, border: 0, background: "transparent" }}
            >
              <b>No data imported</b>
              <p>
                This portfolio entry has not been linked to a project with ingested data yet.
                Data import (documents, assays, drill holes) is available in P2.
              </p>
            </div>
          ) : (
            <div style={{ display: "flex", flexWrap: "wrap" }}>
              <CountStat label="Documents"  value={counts?.documents ?? 0}   icon={IconDoc} />
              <CountStat label="Assays"     value={counts?.assays ?? 0} />
              <CountStat label="Drill holes" value={counts?.drill_holes ?? 0} icon={IconDrill} />
            </div>
          )}
        </div>
      </section>

      {/* ── Future phase callout ── */}
      <div
        style={{
          marginTop: 24,
          padding: "12px 16px",
          border: "1px dashed rgba(17,19,24,.14)",
          borderRadius: 12,
          background: "rgba(245,246,248,.72)",
          display: "flex",
          alignItems: "flex-start",
          gap: 12,
        }}
        role="note"
        aria-label="Upcoming features"
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9aa0aa" strokeWidth="1.5" style={{ flexShrink: 0, marginTop: 1 }} aria-hidden="true">
          <circle cx="12" cy="12" r="10" />
          <path d="M12 8v4M12 16h.01" strokeLinecap="round" />
        </svg>
        <p style={{ margin: 0, fontSize: 12.5, color: "#68707b", lineHeight: 1.6 }}>
          <strong style={{ color: "#111318", fontWeight: 700 }}>More coming soon. </strong>
          Data ingestion is live in the Data tab. Valuation models (P3) and spatial
          mapping (P5) will be available in upcoming phases.
        </p>
      </div>
        </>
      )}
    </main>
  );
}
