"use client";

/**
 * DrawerPrimitives — typed React port of the prototype's drawer markup vocabulary
 * (`.drawer-section` → `.summary-box` → table / kvrows / status-rows / hbars →
 * `.source-line` → `.drawer-actions`). Pure presentational building blocks the
 * per-key drawer content modules compose; no data logic lives here.
 *
 * Sub-tabs (`.dtabs` / `.dtab-panel`) are a self-contained client component
 * (DrawerTabs) that manages the active tab with local useState — the cockpit's
 * market / environment / georisks drawers reuse it.
 */

import { useId, useState } from "react";

import styles from "@/app/site-finder/analysis/[cad]/ptica/ptica.module.css";

// ── Section + summary ─────────────────────────────────────────────────────────

export function DrawerSection({
  heading,
  children,
}: {
  heading?: string;
  children: React.ReactNode;
}) {
  return (
    <div className={styles.drawerSection}>
      {heading && <h4 className={styles.drawerH4}>{heading}</h4>}
      {children}
    </div>
  );
}

export function SummaryBox({ children }: { children: React.ReactNode }) {
  return <div className={styles.summaryBox}>{children}</div>;
}

// ── Key/value rows ────────────────────────────────────────────────────────────

export function DKvRow({
  k,
  v,
  muted,
}: {
  k: React.ReactNode;
  v: React.ReactNode;
  muted?: boolean;
}) {
  return (
    <div className={`${styles.kvrow} ${muted ? styles.kvrowPlaceholder : ""}`}>
      <span className={styles.k}>{k}</span>
      <span className={styles.v}>{v}</span>
    </div>
  );
}

// ── Status row (dot + label + state pill) ─────────────────────────────────────

export type DrawerTone = "ok" | "warn" | "bad" | "muted";

export function StatusRow({
  label,
  state,
  tone = "muted",
}: {
  label: React.ReactNode;
  state: React.ReactNode;
  tone?: DrawerTone;
}) {
  const dotClass =
    tone === "ok"
      ? styles.drDotOk
      : tone === "warn"
        ? styles.drDotWarn
        : tone === "bad"
          ? styles.drDotBad
          : styles.drDotMuted;
  const stateClass =
    tone === "ok"
      ? styles.drStateOk
      : tone === "warn"
        ? styles.drStateWarn
        : tone === "bad"
          ? styles.drStateBad
          : styles.drStateMuted;
  return (
    <div className={styles.statusRow}>
      <span className={`${styles.drDot} ${dotClass}`} aria-hidden="true" />
      <span className={styles.drLabel}>{label}</span>
      <span className={`${styles.drState} ${stateClass}`}>{state}</span>
    </div>
  );
}

// ── Data table ────────────────────────────────────────────────────────────────

export interface DTableColumn {
  header: string;
  /** true → right-aligned mono cell (numbers). */
  num?: boolean;
}

export interface DTableRow {
  cells: React.ReactNode[];
  /** highlight (e.g. totals / target). */
  emphasis?: boolean;
}

export function DTable({
  columns,
  rows,
}: {
  columns: DTableColumn[];
  rows: DTableRow[];
}) {
  return (
    <table className={styles.dtable}>
      <thead>
        <tr>
          {columns.map((c, i) => (
            <th key={i} className={c.num ? styles.thNum : undefined}>
              {c.header}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map((r, ri) => (
          <tr key={ri} className={r.emphasis ? styles.rowTarget : undefined}>
            {r.cells.map((cell, ci) => (
              <td
                key={ci}
                className={columns[ci]?.num ? styles.tdNum : undefined}
              >
                {cell}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ── Horizontal bars (квартирография / contributions) ──────────────────────────

export interface HBarItem {
  name: string;
  /** 0..100 fill width. */
  pct: number;
  value: React.ReactNode;
  tone?: "good" | "bad" | "neutral";
}

export function HBars({ items }: { items: HBarItem[] }) {
  return (
    <div className={styles.hbars}>
      {items.map((b, i) => {
        const fillClass =
          b.tone === "good"
            ? styles.hbarFillGood
            : b.tone === "bad"
              ? styles.hbarFillBad
              : styles.hbarFillNeutral;
        return (
          <div key={i} className={styles.hbar}>
            <span className={styles.hbarName}>{b.name}</span>
            <span className={styles.hbarTrack}>
              <span
                className={`${styles.hbarFill} ${fillClass}`}
                style={{ width: `${Math.max(0, Math.min(100, b.pct))}%` }}
              />
            </span>
            <span className={styles.hbarValue}>{b.value}</span>
          </div>
        );
      })}
    </div>
  );
}

// ── Confidence pill / tag ─────────────────────────────────────────────────────

export function ConfPill({
  level,
  children,
}: {
  level: "high" | "medium" | "low";
  children: React.ReactNode;
}) {
  const cls =
    level === "high"
      ? styles.confPillHigh
      : level === "medium"
        ? styles.confPillMedium
        : styles.confPillLow;
  return <span className={`${styles.confPill} ${cls}`}>{children}</span>;
}

export function Tag({ children }: { children: React.ReactNode }) {
  return <span className={styles.tag}>{children}</span>;
}

// ── Source line + export actions ──────────────────────────────────────────────

export function SourceLine({
  source,
  updated,
}: {
  source: string;
  updated?: string;
}) {
  return (
    <div className={styles.sourceLine}>
      <span>{source}</span>
      {updated && <span>{updated}</span>}
    </div>
  );
}

/**
 * DrawerActions — light export/copy buttons (kept inert: the cockpit's drawer
 * exports are not wired to an endpoint yet, so these are disabled placeholders
 * matching the prototype's `.drawer-actions` rather than fake-firing a download).
 */
export function DrawerActions({ labels }: { labels: string[] }) {
  return (
    <div className={styles.drawerActions}>
      {labels.map((l) => (
        <button
          key={l}
          type="button"
          className={styles.detailBtn}
          disabled
          aria-disabled="true"
          title="Экспорт — в следующем релизе"
        >
          {l}
        </button>
      ))}
    </div>
  );
}

// ── Sub-tabs (.dtabs / .dtab-panel) ───────────────────────────────────────────

export interface DrawerTab {
  id: string;
  label: string;
  content: React.ReactNode;
}

export function DrawerTabs({ tabs }: { tabs: DrawerTab[] }) {
  const [active, setActive] = useState<string>(tabs[0]?.id ?? "");
  const groupId = useId();
  return (
    <>
      <div className={styles.dtabs} role="tablist">
        {tabs.map((t) => (
          <button
            key={t.id}
            type="button"
            role="tab"
            id={`${groupId}-tab-${t.id}`}
            aria-selected={active === t.id}
            aria-controls={`${groupId}-panel-${t.id}`}
            className={active === t.id ? styles.dtabActive : ""}
            onClick={() => setActive(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>
      {tabs.map((t) => (
        <div
          key={t.id}
          role="tabpanel"
          id={`${groupId}-panel-${t.id}`}
          aria-labelledby={`${groupId}-tab-${t.id}`}
          hidden={active !== t.id}
          className={styles.dtabPanel}
        >
          {active === t.id && t.content}
        </div>
      ))}
    </>
  );
}
