"use client";

/**
 * ConfigPanel 헤더/탭/그룹/바인드칩/브레드크럼
 * - 시안 panel-input-new 의 CPHeader, CPTabs, CPGroup, CPBindChip + V4 헤더 brumb 포팅
 */
import React from "react";
import { CPIconBtn } from "./CPPrimitives";
import { CP_ICONS } from "./icons";

const CP_FONT = "var(--v5-font-sans)";
const CP_MONO = "var(--v5-font-mono)";

// ── 헤더 ───────────────────────────────────────────────
export function CPHeader({
  icon,
  title,
  subtitle,
  badge,
  onReset,
}: {
  icon?: React.ReactNode;
  title: React.ReactNode;
  subtitle?: React.ReactNode;
  badge?: React.ReactNode;
  onReset?: () => void;
}) {
  return (
    <div
      style={{
        padding: "10px 12px",
        borderBottom: "1px solid var(--cp-border-subtle)",
        background: "var(--cp-surface)",
        display: "flex",
        alignItems: "center",
        gap: 10,
      }}
    >
      {icon && (
        <div
          style={{
            width: 26,
            height: 26,
            borderRadius: 7,
            background: "linear-gradient(135deg, rgba(var(--v5-primary-rgb),0.15), rgba(var(--v5-cyan-rgb),0.15))",
            border: "1px solid var(--cp-border)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "var(--v5-primary)",
            flexShrink: 0,
          }}
        >
          {icon}
        </div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, lineHeight: 1.1 }}>
          <span
            style={{
              fontSize: 13,
              fontWeight: 700,
              color: "var(--cp-text)",
              letterSpacing: "-0.01em",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {title}
          </span>
          {badge && (
            <span
              style={{
                fontSize: 9.5,
                fontWeight: 700,
                letterSpacing: "0.08em",
                textTransform: "uppercase",
                color: "var(--v5-primary)",
                background: "rgba(var(--v5-primary-rgb),0.08)",
                border: "1px solid rgba(var(--v5-primary-rgb),0.18)",
                padding: "1px 5px",
                borderRadius: 3,
                flexShrink: 0,
              }}
            >
              {badge}
            </span>
          )}
        </div>
        {subtitle && (
          <div
            style={{
              fontSize: 10.5,
              color: "var(--cp-text-muted)",
              marginTop: 2,
              fontFamily: CP_MONO,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {subtitle}
          </div>
        )}
      </div>
      {onReset && (
        <CPIconBtn title="기본값으로 초기화" onClick={onReset}>
          {CP_ICONS.reset}
        </CPIconBtn>
      )}
    </div>
  );
}

// ── 탭 ─────────────────────────────────────────────────
export type CPTabItem = { id: string; label: React.ReactNode; count?: number; dot?: boolean };

export function CPTabs({
  tabs,
  value,
  onChange,
  variant = "underline",
}: {
  tabs: CPTabItem[];
  value: string;
  onChange: (next: string) => void;
  variant?: "underline" | "pill";
}) {
  if (variant === "pill") {
    return (
      <div
        style={{
          padding: "8px 10px",
          display: "flex",
          gap: 4,
          borderBottom: "1px solid var(--cp-border-subtle)",
          background: "var(--cp-bg-subtle)",
        }}
      >
        {tabs.map((t) => {
          const active = t.id === value;
          return (
            <button
              key={t.id}
              type="button"
              onClick={() => onChange(t.id)}
              style={{
                border: "none",
                cursor: "pointer",
                padding: "5px 11px",
                borderRadius: 6,
                fontSize: 11.5,
                fontWeight: active ? 700 : 500,
                color: active ? "#fff" : "var(--cp-text-sec)",
                background: active ? "var(--v5-primary)" : "transparent",
                boxShadow: active ? "0 0 14px rgba(var(--v5-primary-rgb),0.35)" : "none",
                fontFamily: CP_FONT,
              }}
            >
              {t.label}
              {t.count != null && (
                <span
                  style={{
                    marginLeft: 5,
                    fontSize: 10,
                    color: active ? "rgba(255,255,255,.7)" : "var(--cp-text-muted)",
                  }}
                >
                  {t.count}
                </span>
              )}
            </button>
          );
        })}
      </div>
    );
  }
  return (
    <div
      style={{
        display: "flex",
        gap: 0,
        padding: "0 12px",
        borderBottom: "1px solid var(--cp-border-subtle)",
        background: "var(--cp-surface)",
      }}
    >
      {tabs.map((t) => {
        const active = t.id === value;
        return (
          <button
            key={t.id}
            type="button"
            onClick={() => onChange(t.id)}
            style={{
              border: "none",
              background: "transparent",
              cursor: "pointer",
              padding: "9px 10px 8px",
              fontSize: 11.5,
              fontWeight: active ? 700 : 500,
              color: active ? "var(--cp-text)" : "var(--cp-text-sec)",
              borderBottom: active ? "2px solid var(--v5-primary)" : "2px solid transparent",
              marginBottom: -1,
              fontFamily: CP_FONT,
              display: "flex",
              alignItems: "center",
              gap: 5,
            }}
          >
            {t.label}
            {t.dot && (
              <span
                style={{
                  width: 5,
                  height: 5,
                  borderRadius: 999,
                  background: "var(--v5-primary)",
                }}
              />
            )}
          </button>
        );
      })}
    </div>
  );
}

// ── 접이식 그룹 ────────────────────────────────────────
export function CPGroup({
  title,
  desc,
  defaultOpen = true,
  badge,
  children,
}: {
  title: React.ReactNode;
  desc?: React.ReactNode;
  defaultOpen?: boolean;
  badge?: React.ReactNode;
  children?: React.ReactNode;
}) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--cp-border-subtle)" }}>
      <button
        type="button"
        onClick={() => setOpen(!open)}
        style={{
          border: "none",
          background: "transparent",
          cursor: "pointer",
          width: "100%",
          padding: "10px 0",
          display: "flex",
          alignItems: "center",
          gap: 6,
          fontFamily: CP_FONT,
        }}
      >
        <span
          style={{
            transform: open ? "rotate(0deg)" : "rotate(-90deg)",
            transition: "transform .15s var(--v5-ease-move)",
            color: "var(--cp-text-sec)",
            display: "inline-flex",
          }}
        >
          {CP_ICONS.chevron}
        </span>
        <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--cp-text)", letterSpacing: "-0.01em" }}>
          {title}
        </span>
        {badge && <span style={{ fontSize: 10, color: "var(--cp-text-muted)", fontFamily: CP_MONO }}>{badge}</span>}
        {desc && <span style={{ fontSize: 10.5, color: "var(--cp-text-muted)", marginLeft: "auto" }}>{desc}</span>}
      </button>
      <div className="cp-group-content" data-open={open} aria-hidden={!open}>
        <div style={{ padding: "0 0 12px 10px" }}>{children}</div>
      </div>
    </div>
  );
}

// ── 바인드 칩 (data-binding 시각화) ────────────────────
export function CPBindChip({
  table,
  column,
  onClear,
}: {
  table: React.ReactNode;
  column: React.ReactNode;
  onClear?: () => void;
}) {
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        padding: "2px 4px 2px 7px",
        background: "rgba(var(--v5-cyan-rgb),0.08)",
        border: "1px solid rgba(var(--v5-cyan-rgb),0.22)",
        borderRadius: 5,
        fontSize: 11,
        fontFamily: CP_MONO,
        color: "var(--cp-text)",
        maxWidth: "100%",
      }}
    >
      <span style={{ display: "inline-flex", color: "rgb(var(--v5-cyan-rgb))" }}>{CP_ICONS.link}</span>
      <span style={{ fontWeight: 600 }}>{table}</span>
      <span style={{ opacity: 0.4 }}>.</span>
      <span style={{ color: "var(--cp-text-sec)" }}>{column}</span>
      {onClear && (
        <button
          type="button"
          onClick={onClear}
          style={{
            marginLeft: 2,
            border: "none",
            background: "transparent",
            color: "var(--cp-text-muted)",
            cursor: "pointer",
            padding: 2,
            borderRadius: 3,
            display: "inline-flex",
          }}
        >
          {CP_ICONS.close}
        </button>
      )}
    </div>
  );
}

// ── kind ▸ type 헤더 brumb (좌/우 분할 · 양쪽 클릭) ──────
export type CPCrumbType = { id: string; name: string; desc?: string; icon?: React.ReactNode; col?: string };
export type CPCrumbKind = { id: string; name: string; icon?: React.ReactNode };

export function CPCrumb({
  kinds,
  currentKind,
  onChangeKind,
  types,
  value,
  onChange,
}: {
  kinds: CPCrumbKind[];
  currentKind: string;
  onChangeKind: (next: string) => void;
  types: CPCrumbType[];
  value: string;
  onChange: (next: string) => void;
}) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef<HTMLDivElement>(null);

  const kind = kinds.find((k) => k.id === currentKind) || kinds[0];
  const current = types.find((t) => t.id === value) || types[0];
  const hasMultipleKinds = kinds.length > 1;

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onEsc = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onEsc);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onEsc);
    };
  }, [open]);

  const toggle = () => setOpen((v) => !v);

  return (
    <div className="cp-bar" ref={ref} data-open={open}>
      <div className="cp-crumb-split">
        {/* 좌측 : kind — 클릭 시 통합 팝오버 토글 */}
        <div className="cp-crumb-side cp-crumb-kind-slot">
          <button
            type="button"
            className="cp-crumb-side-btn cp-crumb-kind-btn"
            data-open={open}
            data-clickable={hasMultipleKinds}
            onClick={() => hasMultipleKinds && toggle()}
          >
            {kind?.icon && <span className="cp-crumb-kind-icon">{kind.icon}</span>}
            <span className="cp-crumb-kind-name">{kind?.name}</span>
            {hasMultipleKinds && <span className="cp-crumb-kind-chev">{CP_ICONS.chevron}</span>}
          </button>
        </div>

        <div className="cp-crumb-divider" aria-hidden="true" />

        {/* 우측 : type — 클릭 시 통합 팝오버 토글 */}
        <div className="cp-crumb-side cp-crumb-type-slot">
          <button
            type="button"
            className="cp-crumb-side-btn cp-crumb-type-btn"
            data-open={open}
            onClick={toggle}
          >
            <span className="cp-crumb-type-icon">{current?.icon}</span>
            <div className="cp-crumb-type-text">
              <div className="cp-crumb-type-name">{current?.name}</div>
              {current?.desc && <div className="cp-crumb-type-desc">{current.desc}</div>}
            </div>
            <span className="cp-crumb-type-chev">{CP_ICONS.chevron}</span>
          </button>
        </div>
      </div>

      {/* 통합 팝오버 — kinds(좌) + types(우). kind 선택은 popover 안 닫고 type 갱신만 */}
      {open && (
        <div className="cp-pop cp-pop-combined">
          {hasMultipleKinds && (
            <div className="cp-pop-col cp-pop-kinds-col">
              {kinds.map((k, i) => (
                <button
                  key={k.id}
                  type="button"
                  className="cp-pop-kind-item"
                  data-active={currentKind === k.id}
                  onClick={() => onChangeKind(k.id)}
                  style={{ animationDelay: `${i * 18}ms` }}
                >
                  {k.icon && <span className="cp-pop-kind-item-icon">{k.icon}</span>}
                  <span className="cp-pop-kind-item-name">{k.name}</span>
                </button>
              ))}
            </div>
          )}
          <div className="cp-pop-col cp-pop-types-col" key={currentKind}>
            {types.map((t, i) => (
              <button
                key={t.id}
                type="button"
                className="cp-pop-type"
                data-active={value === t.id}
                onClick={() => {
                  onChange(t.id);
                  setOpen(false);
                }}
                style={{ animationDelay: `${i * 22}ms` }}
              >
                <span className="cp-pop-type-icon">{t.icon}</span>
                <div className="cp-pop-type-text">
                  <div className="cp-pop-type-name">{t.name}</div>
                  {t.desc && <div className="cp-pop-type-desc">{t.desc}</div>}
                </div>
                {t.col && <span className="cp-pop-type-col">{t.col}</span>}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ── 형식 트리거 (본문 안에서 [형식 · ▾]) ───────────────
export type CPFormatItem = { id: string; name: string; desc?: string; icon?: React.ReactNode };

export function CPFormatTrigger({
  formats,
  value,
  onChange,
}: {
  formats: CPFormatItem[];
  value: string;
  onChange: (next: string) => void;
}) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef<HTMLDivElement>(null);
  const current = formats.find((f) => f.id === value) || formats[0];
  const hasMultiple = formats.length > 1;

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  return (
    <div className="cp-fmt-head">
      <span className="cp-fmt-head-cap">형식</span>
      <span className="cp-fmt-head-dot">·</span>
      <div style={{ position: "relative" }} ref={ref}>
        <button
          type="button"
          className="cp-fmt-trigger"
          data-open={open}
          onClick={() => hasMultiple && setOpen(!open)}
          style={{ cursor: hasMultiple ? "pointer" : "default" }}
        >
          <span className="cp-fmt-trigger-icon">{current?.icon}</span>
          <span className="cp-fmt-trigger-name">{current?.name}</span>
          {hasMultiple && <span className="cp-fmt-trigger-chev">▾</span>}
        </button>
        {open && (
          <div className="cp-fmt-pop">
            {formats.map((f) => (
              <button
                key={f.id}
                type="button"
                className="cp-fmt-pop-item"
                data-active={f.id === value}
                onClick={() => {
                  onChange(f.id);
                  setOpen(false);
                }}
              >
                <span className="cp-fmt-pop-item-icon">{f.icon}</span>
                <div className="cp-fmt-pop-item-text">
                  <div className="cp-fmt-pop-item-name">{f.name}</div>
                  {f.desc && <div className="cp-fmt-pop-item-desc">{f.desc}</div>}
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
      {current?.desc && <span className="cp-fmt-head-desc">{current.desc}</span>}
    </div>
  );
}
