"use client";

import { useCallback, useEffect, useRef, useState } from "react";

import {
  isSoftLaunchClientEnabled,
  postSoftLaunchReadingFeedback,
  queueSoftLaunchTelemetry,
  type SoftLaunchReadingReaction,
} from "@/lib/soft-launch-client";

type Props = {
  sectionKey: string;
  chartId: string;
  chartFingerprint?: string;
  children: React.ReactNode;
};

function feedbackStorageKey(chartId: string, sectionKey: string): string {
  return `ctkp_sl_fb_v1_${chartId}_${sectionKey}`.slice(0, 120);
}

function SoftLaunchSectionFeedback({
  sectionKey,
  chartId,
  chartFingerprint,
}: {
  sectionKey: string;
  chartId: string;
  chartFingerprint?: string;
}) {
  const [done, setDone] = useState(false);
  const [busy, setBusy] = useState(false);
  const [commentOpen, setCommentOpen] = useState(false);
  const [comment, setComment] = useState("");

  useEffect(() => {
    if (typeof sessionStorage === "undefined") return;
    try {
      if (sessionStorage.getItem(feedbackStorageKey(chartId, sectionKey)) === "1") setDone(true);
    } catch {
      /* ignore */
    }
  }, [chartId, sectionKey]);

  const send = useCallback(
    async (reaction: SoftLaunchReadingReaction) => {
      if (busy || done) return;
      setBusy(true);
      try {
        await postSoftLaunchReadingFeedback({
          chartId,
          chartFingerprint,
          sectionKey,
          reaction,
          comment: comment.trim() || undefined,
        });
        try {
          sessionStorage.setItem(feedbackStorageKey(chartId, sectionKey), "1");
        } catch {
          /* ignore */
        }
        setDone(true);
      } finally {
        setBusy(false);
      }
    },
    [busy, chartFingerprint, chartId, comment, done, sectionKey],
  );

  if (!isSoftLaunchClientEnabled()) return null;

  return (
    <div className="mt-8 border-t border-[color:rgba(90,72,52,0.14)] pt-5 print:hidden">
      <p className="font-ctkp-serif text-[11px] tracking-[0.06em] text-[color:var(--ctkp-narrative-caption)]">
        Mức khớp với bạn ở mục này? (tuỳ chọn)
      </p>
      {done ?
        <p className="mt-2 font-ctkp-serif text-[12px] text-[color:var(--ctkp-narrative-ink)] opacity-80">Đã ghi nhận — cảm ơn bạn.</p>
      : <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              disabled={busy}
              onClick={() => void send("rat_dung")}
              className="rounded-sm border border-[color:rgba(90,72,52,0.28)] bg-[rgba(255,252,245,0.35)] px-3 py-1.5 font-ctkp-serif text-[12px] text-[color:var(--ctkp-narrative-ink)] transition-colors hover:border-[color:rgba(90,72,52,0.45)] disabled:opacity-40"
            >
              Đúng
            </button>
            <button
              type="button"
              disabled={busy}
              onClick={() => void send("kha_dung")}
              className="rounded-sm border border-[color:rgba(90,72,52,0.28)] bg-[rgba(255,252,245,0.35)] px-3 py-1.5 font-ctkp-serif text-[12px] text-[color:var(--ctkp-narrative-ink)] transition-colors hover:border-[color:rgba(90,72,52,0.45)] disabled:opacity-40"
            >
              Khá đúng
            </button>
            <button
              type="button"
              disabled={busy}
              onClick={() => void send("chua_dung")}
              className="rounded-sm border border-[color:rgba(90,72,52,0.28)] bg-[rgba(255,252,245,0.35)] px-3 py-1.5 font-ctkp-serif text-[12px] text-[color:var(--ctkp-narrative-ink)] transition-colors hover:border-[color:rgba(90,72,52,0.45)] disabled:opacity-40"
            >
              Chưa đúng
            </button>
          </div>
          <button
            type="button"
            disabled={busy}
            onClick={() => setCommentOpen((v) => !v)}
            className="self-start font-sans text-[11px] text-[color:var(--ctkp-narrative-caption)] underline-offset-4 hover:underline"
          >
            {commentOpen ? "Ẩn ghi chú" : "Ghi chú ngắn (tuỳ chọn)"}
          </button>
          {commentOpen ?
            <label className="flex w-full max-w-md flex-col gap-1 sm:ml-0">
              <span className="sr-only">Ghi chú phản hồi</span>
              <textarea
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                maxLength={560}
                rows={2}
                disabled={busy}
                placeholder="Một vài dòng nếu bạn muốn cụ thể hơn…"
                className="resize-y rounded-sm border border-[color:rgba(90,72,52,0.22)] bg-[rgba(255,252,245,0.45)] px-2 py-1.5 font-sans text-[12px] text-[color:var(--ctkp-narrative-ink)] placeholder:text-[color:rgba(90,72,52,0.35)]"
              />
            </label>
          : null}
        </div>
      }
    </div>
  );
}

export function SoftLaunchOverviewSectionChrome({ sectionKey, chartId, chartFingerprint, children }: Props) {
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isSoftLaunchClientEnabled()) return;
    const el = rootRef.current;
    if (!el) return;
    let wasVisible = false;
    let enteredAt: number | null = null;
    const io = new IntersectionObserver(
      (entries) => {
        const en = entries[0];
        if (!en) return;
        const vis = en.isIntersecting && en.intersectionRatio >= 0.1;
        if (vis && !wasVisible) {
          wasVisible = true;
          enteredAt = Date.now();
        } else if (!vis && wasVisible && enteredAt != null) {
          wasVisible = false;
          const ms = Date.now() - enteredAt;
          enteredAt = null;
          if (ms >= 500) {
            queueSoftLaunchTelemetry({
              chartId,
              chartFingerprint,
              sectionKey,
              eventType: "overview_section_dwell",
              payload: { ms },
            });
            if (ms < 1600) {
              queueSoftLaunchTelemetry({
                chartId,
                chartFingerprint,
                sectionKey,
                eventType: "overview_section_quick_leave",
                payload: { ms },
              });
            }
            if (ms >= 22_000) {
              queueSoftLaunchTelemetry({
                chartId,
                chartFingerprint,
                sectionKey,
                eventType: "overview_section_slow_read",
                payload: { ms },
              });
            }
          }
        }
      },
      { threshold: [0, 0.1, 0.22] },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [chartFingerprint, chartId, sectionKey]);

  const onCopyCapture = useCallback(() => {
    if (!isSoftLaunchClientEnabled()) return;
    const t = typeof window !== "undefined" ? (window.getSelection()?.toString().trim() ?? "") : "";
    if (t.length < 14) return;
    queueSoftLaunchTelemetry({
      chartId,
      chartFingerprint,
      sectionKey,
      eventType: "overview_section_copy",
      payload: { approxChars: Math.min(t.length, 900) },
    });
  }, [chartFingerprint, chartId, sectionKey]);

  if (!isSoftLaunchClientEnabled()) return <>{children}</>;

  return (
    <div ref={rootRef} onCopyCapture={onCopyCapture} className="soft-launch-reading-section">
      {children}
      <SoftLaunchSectionFeedback
        sectionKey={sectionKey}
        chartId={chartId}
        chartFingerprint={chartFingerprint}
      />
    </div>
  );
}

export function buildSoftLaunchOverviewSectionKey(sec: {
  readonly sectionId?: string;
  readonly canonicalKey?: string;
  readonly title: string;
}): string {
  const raw = sec.sectionId?.trim() || sec.canonicalKey?.trim() || sec.title.trim().replace(/\s+/g, "_").toLowerCase();
  const k = raw.replace(/[^a-z0-9._-]/gi, "_").slice(0, 64);
  return k || "section";
}
