"use client";

import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import Cookies from "js-cookie";
import {
  X,
  Clock,
  ListPlus,
  Flag,
  ChevronRight,
  ChevronLeft,
  CheckCircle2,
  AlertCircle,
  Loader2,
  Plus,
  Check,
} from "lucide-react";
import {
  watchLaterService,
  reportService,
  type ReportReason,
} from "@/services/contentActionService";
import { playlistService, type Playlist } from "@/services/playlistService";
import { useRequireAuth } from "@/hooks/useRequireAuth";
import { useTranslation } from "@/i18n";

/* ── Context type ────────────────────────────────────────────────────────── */

export interface ContentActionContext {
  contentId: string;
  contentType: number;
  channelId: string; // content creator's channel_id
  channelUserId: string; // content creator's user_id (for report)
  episodeId?: string;
  title: string;
  thumbnail?: string;
  channelName?: string;
}

interface Props {
  context: ContentActionContext;
  onClose: () => void;
}

type Screen =
  | "main"
  | "playlist"
  | "create-playlist"
  | "report-reasons"
  | "report-message";

/* ── Mosaic thumbnail (up to 4 images in a 2×2 grid) ────────────────────── */
function PlaylistMosaic({
  images,
  size = 44,
}: {
  images: string[];
  size?: number;
}) {
  const imgs = images.slice(0, 4);
  if (imgs.length === 0) {
    return (
      <div
        className="rounded-xl flex items-center justify-center shrink-0"
        style={{
          width: size,
          height: size,
          background: "var(--deep)",
        }}
      >
        <ListPlus size={size * 0.4} color="#555" strokeWidth={1.5} />
      </div>
    );
  }
  if (imgs.length === 1) {
    return (
      <div
        className="relative rounded-xl overflow-hidden shrink-0"
        style={{ width: size, height: size }}
      >
        <Image
          src={imgs[0]}
          alt=""
          fill
          className="object-cover"
          unoptimized
          sizes={`${size}px`}
        />
      </div>
    );
  }
  return (
    <div
      className="grid grid-cols-2 rounded-xl overflow-hidden shrink-0"
      style={{ width: size, height: size, gap: 1.5 }}
    >
      {Array.from({ length: 4 }).map((_, i) => (
        <div
          key={i}
          className="relative overflow-hidden"
          style={{ background: "var(--deep)" }}
        >
          {imgs[i] && (
            <Image
              src={imgs[i]}
              alt=""
              fill
              className="object-cover"
              unoptimized
              sizes={`${size / 2}px`}
            />
          )}
        </div>
      ))}
    </div>
  );
}

/* ── Sheet wrapper ───────────────────────────────────────────────────────── */
function Sheet({
  children,
  onClose,
}: {
  children: React.ReactNode;
  onClose?: () => void;
}) {
  useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "";
    };
  }, []);

  return (
    <>
      <div
        className="fixed inset-0 z-[200]"
        style={{
          background: "rgba(0,0,0,0.74)",
          backdropFilter: "blur(10px)",
          animation: "cas-fade 0.2s ease both",
        }}
        onClick={onClose}
      />
      <div
        className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col"
        style={{
          maxWidth: "680px",
          margin: "0 auto",
          maxHeight: "88vh",
          background: "var(--sheet-bg)",
          borderRadius: "20px 20px 0 0",
          border: "1px solid var(--sheet-border)",
          borderBottom: "none",
          boxShadow:
            "0 -24px 64px rgba(0,0,0,0.7), inset 0 1px 0 var(--border-soft)",
          animation: "cas-up 0.35s cubic-bezier(0.32,1.2,0.56,1) both",
        }}
      >
        {/* Drag handle */}
        <div className="flex justify-center pt-2.5 pb-0 shrink-0">
          <div
            className="w-9 h-[3px] rounded-full"
            style={{ background: "var(--sheet-handle)" }}
          />
        </div>
        {children}
      </div>

      <style>{`
        @keyframes cas-fade { from{opacity:0} to{opacity:1} }
        @keyframes cas-up   { from{transform:translateY(100%)} to{transform:translateY(0)} }
        @keyframes cas-item { from{opacity:0;transform:translateX(-8px)} to{opacity:1;transform:translateX(0)} }
        @keyframes cas-spin-in { from{opacity:0;transform:scale(0.7) rotate(-10deg)} to{opacity:1;transform:scale(1) rotate(0)} }
      `}</style>
    </>
  );
}

/* ── Section header row ──────────────────────────────────────────────────── */
function SheetHeader({
  title,
  onBack,
  onClose,
  sub,
}: {
  title: string;
  onBack?: () => void;
  onClose?: () => void;
  sub?: string;
}) {
  return (
    <div
      className="flex items-center gap-3 px-5 py-3.5 shrink-0"
      style={{ borderBottom: "1px solid var(--border)" }}
    >
      {onBack && (
        <button
          onClick={onBack}
          className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
          style={{ background: "var(--btn-ghost-hover)" }}
        >
          <ChevronLeft size={14} color="#aaa" strokeWidth={2.5} />
        </button>
      )}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-bold tracking-tight leading-tight" style={{ color: "var(--text-primary)" }}>
          {title}
        </p>
        {sub && (
          <p className="text-[10px] mt-0.5 truncate" style={{ color: "var(--text-muted)" }}>
            {sub}
          </p>
        )}
      </div>
      {onClose && (
        <button
          onClick={onClose}
          className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
          style={{ background: "var(--btn-ghost-hover)" }}
        >
          <X size={13} color="#888" />
        </button>
      )}
    </div>
  );
}

/* ── Toast notification (internal) ──────────────────────────────────────── */
function Toast({ msg, ok }: { msg: string; ok: boolean }) {
  return (
    <div
      className="fixed bottom-6 left-1/2 z-[210] flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-semibold text-[#ffffff] shadow-xl"
      style={{
        transform: "translateX(-50%)",
        background: ok ? "rgba(16,185,129,0.92)" : "rgba(244,63,94,0.92)",
        backdropFilter: "blur(8px)",
        animation: "cas-spin-in 0.3s cubic-bezier(0.34,1.5,0.64,1) both",
        whiteSpace: "nowrap",
      }}
    >
      {ok ? (
        <CheckCircle2 size={13} strokeWidth={2.5} />
      ) : (
        <AlertCircle size={13} strokeWidth={2.5} />
      )}
      {msg}
    </div>
  );
}

/* ══════════════════════════════════════════════════════════════════════════
   MAIN MODAL
══════════════════════════════════════════════════════════════════════════ */

export function ContentActionsModal({ context, onClose }: Props) {
  const { t } = useTranslation();
  const [screen, setScreen] = useState<Screen>("main");
  const [toast, setToast] = useState<{ msg: string; ok: boolean } | null>(null);
  const [wlLoading, setWlLoading] = useState(false);
  const [wlAdded, setWlAdded] = useState(false);

  /* Playlist state */
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [plLoading, setPlLoading] = useState(false);
  const [addedPls, setAddedPls] = useState<Set<string>>(new Set());
  const [newTitle, setNewTitle] = useState("");
  const [creating, setCreating] = useState(false);

  /* Report state */
  const [reasons, setReasons] = useState<ReportReason[]>([]);
  const [rLoading, setRLoading] = useState(false);
  const [selectedReason, setSelectedReason] = useState<ReportReason | null>(
    null,
  );
  const [reportMsg, setReportMsg] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const myChannelId = Cookies.get("channel_id") ?? "";
  const requireAuth = useRequireAuth();

  /* Auto-hide toast */
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2400);
    return () => clearTimeout(t);
  }, [toast]);

  /* ── Watch Later ── */
  const handleWatchLater = async () => {
    setWlLoading(true);
    try {
      const type = wlAdded ? 2 : 1;
      const res = await watchLaterService.toggle({
        contentType: context.contentType,
        contentId: context.contentId,
        episodeId: context.episodeId,
        type,
      });
      if (res.status === 200) {
        setWlAdded(!wlAdded);
        setToast({
          msg: wlAdded
            ? t("action_removedWatchLater")
            : t("action_addedWatchLater"),
          ok: true,
        });
      } else {
        setToast({ msg: res.message ?? "Failed", ok: false });
      }
    } catch {
      setToast({ msg: "Something went wrong", ok: false });
    } finally {
      setWlLoading(false);
    }
  };

  /* ── Fetch playlists ── */
  const openPlaylists = () => {
    setScreen("playlist");
    if (playlists.length > 0) return;
    setPlLoading(true);
    playlistService
      .getMyPlaylists(myChannelId)
      .then(setPlaylists)
      .catch(() => {})
      .finally(() => setPlLoading(false));
  };

  /* ── Add/remove from playlist ── */
  const togglePlaylist = async (pl: Playlist) => {
    const isAdded = addedPls.has(pl.id);
    const next = new Set(addedPls);
    if (isAdded) next.delete(pl.id);
    else next.add(pl.id);
    setAddedPls(next);

    try {
      await playlistService.addOrRemove({
        channelId: myChannelId,
        playlistId: pl.id,
        contentType: context.contentType,
        contentId: context.contentId,
        episodeId: context.episodeId,
        type: isAdded ? 2 : 1,
      });
      setToast({
        msg: isAdded ? t("action_removedPlaylist") : t("action_addedPlaylist"),
        ok: true,
      });
    } catch {
      if (isAdded) next.add(pl.id);
      else next.delete(pl.id);
      setAddedPls(new Set(next));
      setToast({ msg: t("action_failedPlaylist"), ok: false });
    }
  };

  /* ── Create playlist ── */
  const handleCreate = async () => {
    if (!newTitle.trim()) return;
    setCreating(true);
    try {
      const res = await playlistService.create({
        channelId: myChannelId,
        playlistType: context.contentType === 2 ? 2 : 1, // 2=music, 1=others
        title: newTitle.trim(),
      });
      if (res.status === 200) {
        setToast({ msg: t("playlist_created"), ok: true });
        setNewTitle("");
        setScreen("playlist");
        setPlLoading(true);
        playlistService
          .getMyPlaylists(myChannelId)
          .then(setPlaylists)
          .finally(() => setPlLoading(false));
      } else {
        setToast({ msg: res.message ?? "Creation failed", ok: false });
      }
    } catch {
      setToast({ msg: "Could not create playlist", ok: false });
    } finally {
      setCreating(false);
    }
  };

  /* ── Fetch report reasons ── */
  const openReport = () => {
    setScreen("report-reasons");
    if (reasons.length > 0) return;
    setRLoading(true);
    reportService
      .getReasons()
      .then(setReasons)
      .catch(() => {})
      .finally(() => setRLoading(false));
  };

  /* ── Submit report ── */
  const handleReport = async () => {
    if (!selectedReason || !reportMsg.trim()) return;
    setSubmitting(true);
    try {
      const res = await reportService.submit({
        reportUserId: context.channelUserId,
        contentId: context.contentId,
        contentType: context.contentType,
        message: `${selectedReason.reason}: ${reportMsg.trim()}`,
      });
      if (res.status === 200) {
        setToast({ msg: t("report_submitted"), ok: true });
        setTimeout(onClose, 1800);
      } else {
        setToast({ msg: res.message ?? "Submission failed", ok: false });
      }
    } catch {
      setToast({ msg: "Could not submit report", ok: false });
    } finally {
      setSubmitting(false);
    }
  };

  /* ══════════════════════════════════════════════════════════════════════
     SCREEN: MAIN
  ══════════════════════════════════════════════════════════════════════ */
  if (screen === "main") {
    const actions = [
      {
        id: "watch-later",
        icon: <Clock size={18} strokeWidth={1.8} color="var(--accent)" />,
        label: wlAdded
          ? t("action_removeWatchLater")
          : t("action_saveWatchLater"),
        sub: wlAdded ? t("action_alreadyInList") : t("action_watchAnytime"),
        onClick: () => requireAuth(handleWatchLater),
        loading: wlLoading,
        accent: true,
      },
      {
        id: "playlist",
        icon: <ListPlus size={18} strokeWidth={1.8} color="#60a5fa" />,
        label: t("action_addToPlaylist"),
        sub: t("action_organiseContent"),
        onClick: () => requireAuth(openPlaylists),
        accent: false,
      },
      {
        id: "report",
        icon: <Flag size={18} strokeWidth={1.8} color="#f43f5e" />,
        label: t("action_report"),
        sub: t("action_flagContent"),
        onClick: openReport,
        accent: false,
      },
    ];

    return (
      <Sheet onClose={onClose}>
        {/* Content preview strip */}
        <div className="flex items-center gap-3 px-5 pt-4 pb-3 shrink-0">
          {context.thumbnail && (
            <div
              className="relative w-12 h-9 rounded-lg overflow-hidden shrink-0"
              style={{ background: "var(--deep)" }}
            >
              <Image
                src={context.thumbnail}
                alt=""
                fill
                className="object-cover"
                unoptimized
                sizes="48px"
              />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="text-xs font-semibold truncate" style={{ color: "var(--text-primary)" }}>
              {context.title}
            </p>
            {context.channelName && (
              <p
                className="text-[10px] mt-0.5 truncate"
                style={{ color: "var(--text-muted)" }}
              >
                {context.channelName}
              </p>
            )}
          </div>
          <button
            onClick={onClose}
            className="w-7 h-7 rounded-full flex items-center justify-center"
            style={{ background: "var(--btn-ghost-hover)" }}
          >
            <X size={13} color="#888" />
          </button>
        </div>

        <div
          className="h-px mx-5"
          style={{ background: "var(--border)" }}
        />

        <div className="flex-1 overflow-y-auto pb-8 pt-1">
          {actions.map((a, i) => (
            <button
              key={i}
              onClick={a.onClick}
              disabled={a.loading}
              className="w-full flex items-center gap-4 px-5 py-3.5 transition-all duration-150 active:scale-[0.98] disabled:opacity-60 text-left"
              style={{
                animation: `cas-item 0.28s ease both ${i * 60}ms`,
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLElement).style.background =
                  "var(--btn-ghost)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLElement).style.background =
                  "transparent";
              }}
            >
              <div
                className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0"
                style={{ background: "var(--deep)" }}
              >
                {a.loading ? (
                  <Loader2 size={16} className="animate-spin" color="#888" />
                ) : (
                  a.icon
                )}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-[13px] font-semibold leading-tight" style={{ color: "var(--text-primary)" }}>
                  {a.label}
                </p>
                <p className="text-[10px] mt-0.5" style={{ color: "var(--text-muted)" }}>
                  {a.sub}
                </p>
              </div>
              {!a.loading && a.id !== "report" && (
                <ChevronRight size={14} color="#444" strokeWidth={2} />
              )}
            </button>
          ))}
        </div>

        {toast && <Toast msg={toast.msg} ok={toast.ok} />}
      </Sheet>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     SCREEN: PLAYLIST LIST
  ══════════════════════════════════════════════════════════════════════ */
  if (screen === "playlist") {
    return (
      <Sheet>
        <SheetHeader
          title={t("action_addToPlaylist")}
          sub={context.title}
          onBack={() => setScreen("main")}
          onClose={onClose}
        />

        {/* Create new button */}
        <button
          onClick={() => setScreen("create-playlist")}
          className="flex items-center gap-3 px-5 py-3.5 w-full transition-all"
          style={{ borderBottom: "1px solid var(--border)" }}
          onMouseEnter={(e) => {
            (e.currentTarget as HTMLElement).style.background =
              "rgba(var(--accent-rgb),0.05)";
          }}
          onMouseLeave={(e) => {
            (e.currentTarget as HTMLElement).style.background = "transparent";
          }}
        >
          <div
            className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
            style={{
              background: "rgba(var(--accent-rgb),0.1)",
              border: "1px solid rgba(var(--accent-rgb),0.2)",
            }}
          >
            <Plus size={18} color="var(--accent)" strokeWidth={2.5} />
          </div>
          <div>
            <p className="text-[13px] font-bold" style={{ color: "var(--text-primary)" }}>
              {t("playlist_new")}
            </p>
            <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
              {t("playlist_createNew")}
            </p>
          </div>
          <ChevronRight size={14} color="#555" className="ml-auto" />
        </button>

        <div className="flex-1 overflow-y-auto pb-8">
          {plLoading ? (
            <div className="flex justify-center py-10">
              <Loader2
                size={22}
                className="animate-spin"
                color="rgba(var(--accent-rgb),0.6)"
              />
            </div>
          ) : playlists.length === 0 ? (
            <div className="flex flex-col items-center gap-2 py-12">
              <ListPlus size={28} color="#333" strokeWidth={1.2} />
              <p className="text-xs" style={{ color: "var(--text-muted)" }}>
                {t("playlist_noPlaylists")}
              </p>
            </div>
          ) : (
            playlists.map((pl, i) => {
              const added = addedPls.has(pl.id);
              return (
                <button
                  key={pl.id}
                  onClick={() => togglePlaylist(pl)}
                  className="flex items-center gap-3 px-5 py-3 w-full transition-all active:scale-[0.98]"
                  style={{ animation: `cas-item 0.25s ease both ${i * 50}ms` }}
                  onMouseEnter={(e) => {
                    (e.currentTarget as HTMLElement).style.background =
                      "var(--btn-ghost)";
                  }}
                  onMouseLeave={(e) => {
                    (e.currentTarget as HTMLElement).style.background =
                      "transparent";
                  }}
                >
                  <PlaylistMosaic images={pl.images} size={48} />
                  <div className="flex-1 min-w-0 text-left">
                    <p className="text-[13px] font-semibold truncate" style={{ color: "var(--text-primary)" }}>
                      {pl.title}
                    </p>
                    <p className="text-[10px] mt-0.5" style={{ color: "var(--text-muted)" }}>
                      {pl.images.length}{" "}
                      {pl.images.length !== 1
                        ? t("playlist_items")
                        : t("playlist_item")}
                    </p>
                  </div>
                  <div
                    className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 transition-all duration-200"
                    style={{
                      background: added
                        ? "var(--accent)"
                        : "var(--border-soft)",
                      border: added
                        ? "none"
                        : "1.5px solid var(--border)",
                    }}
                  >
                    {added && <Check size={11} color="#fff" strokeWidth={3} />}
                  </div>
                </button>
              );
            })
          )}
        </div>

        {toast && <Toast msg={toast.msg} ok={toast.ok} />}
      </Sheet>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     SCREEN: CREATE PLAYLIST
  ══════════════════════════════════════════════════════════════════════ */
  if (screen === "create-playlist") {
    return (
      <Sheet>
        <SheetHeader
          title={t("playlist_create")}
          onBack={() => setScreen("playlist")}
          onClose={onClose}
        />

        <div className="flex flex-col gap-4 px-5 py-5 flex-1">
          <div>
            <label
              className="text-[10px] font-bold uppercase tracking-widest mb-2 block"
              style={{ color: "var(--text-muted)" }}
            >
              {t("playlist_name")}
            </label>
            <input
              type="text"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") handleCreate();
              }}
              placeholder={t("playlist_placeholder")}
              maxLength={60}
              autoFocus
              className="w-full px-4 py-3 rounded-xl text-sm outline-none transition-all"
              style={{
                color: "var(--text-primary)",
                background: "var(--deep)",
                border: "1.5px solid var(--border)",
                caretColor: "var(--accent)",
              }}
              onFocus={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "rgba(var(--accent-rgb),0.45)";
              }}
              onBlur={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--border)";
              }}
            />
            <p
              className="text-[10px] mt-1.5 text-right"
              style={{ color: "#444" }}
            >
              {newTitle.length}/60
            </p>
          </div>

          <button
            onClick={handleCreate}
            disabled={!newTitle.trim() || creating}
            className="w-full h-12 rounded-xl text-sm font-black text-[#ffffff] transition-all active:scale-[0.98] disabled:opacity-30 flex items-center justify-center gap-2 mt-2"
            style={{
              background: "linear-gradient(135deg,#f59e0b,var(--accent))",
              boxShadow: newTitle.trim()
                ? "0 4px 22px rgba(var(--accent-rgb),0.35)"
                : "none",
            }}
          >
            {creating ? (
              <Loader2 size={16} className="animate-spin" />
            ) : (
              <Plus size={16} strokeWidth={2.5} />
            )}
            {creating ? t("playlist_creating") : t("playlist_create")}
          </button>
        </div>

        {toast && <Toast msg={toast.msg} ok={toast.ok} />}
      </Sheet>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     SCREEN: REPORT — REASON LIST
  ══════════════════════════════════════════════════════════════════════ */
  if (screen === "report-reasons") {
    return (
      <Sheet>
        <SheetHeader
          title={t("action_report")}
          sub={t("report_selectReason")}
          onBack={() => setScreen("main")}
          onClose={onClose}
        />

        <div className="flex-1 overflow-y-auto pb-6 pt-1">
          {rLoading ? (
            <div className="flex justify-center py-10">
              <Loader2
                size={22}
                className="animate-spin"
                color="rgba(244,63,94,0.6)"
              />
            </div>
          ) : (
            reasons.map((r, i) => (
              <button
                key={r.id}
                onClick={() => {
                  setSelectedReason(r);
                  setScreen("report-message");
                }}
                className="flex items-center gap-3 px-5 py-3.5 w-full transition-all text-left"
                style={{ animation: `cas-item 0.25s ease both ${i * 40}ms` }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLElement).style.background =
                    "rgba(244,63,94,0.04)";
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLElement).style.background =
                    "transparent";
                }}
              >
                <div
                  className="w-1.5 h-1.5 rounded-full shrink-0"
                  style={{ background: "rgba(244,63,94,0.6)" }}
                />
                <p className="text-[13px] flex-1" style={{ color: "var(--text-primary)" }}>{r.reason}</p>
                <ChevronRight size={13} color="#444" strokeWidth={2} />
              </button>
            ))
          )}
        </div>

        {toast && <Toast msg={toast.msg} ok={toast.ok} />}
      </Sheet>
    );
  }

  /* ══════════════════════════════════════════════════════════════════════
     SCREEN: REPORT — MESSAGE
  ══════════════════════════════════════════════════════════════════════ */
  if (screen === "report-message") {
    return (
      <Sheet>
        <SheetHeader
          title={selectedReason?.reason ?? t("action_report")}
          sub={t("report_addDetails")}
          onBack={() => setScreen("report-reasons")}
          onClose={onClose}
        />

        <div className="flex flex-col gap-4 px-5 py-5 flex-1">
          <div>
            <label
              className="text-[10px] font-bold uppercase tracking-widest mb-2 block"
              style={{ color: "var(--text-muted)" }}
            >
              {t("report_details")} <span style={{ color: "#f43f5e" }}>*</span>
            </label>
            <textarea
              value={reportMsg}
              onChange={(e) => setReportMsg(e.target.value)}
              placeholder={t("report_placeholder")}
              rows={4}
              maxLength={500}
              autoFocus
              className="w-full px-4 py-3 rounded-xl text-sm outline-none transition-all resize-none"
              style={{
                color: "var(--text-primary)",
                background: "var(--deep)",
                border: "1.5px solid var(--border)",
                caretColor: "#f43f5e",
                lineHeight: 1.5,
              }}
              onFocus={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "rgba(244,63,94,0.4)";
              }}
              onBlur={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--border)";
              }}
            />
            <p
              className="text-[10px] mt-1.5 text-right"
              style={{ color: "#444" }}
            >
              {reportMsg.length}/500
            </p>
          </div>

          <div
            className="flex items-start gap-2.5 px-3 py-2.5 rounded-xl"
            style={{
              background: "rgba(244,63,94,0.06)",
              border: "1px solid rgba(244,63,94,0.12)",
            }}
          >
            <AlertCircle
              size={13}
              color="#f43f5e"
              strokeWidth={1.8}
              className="shrink-0 mt-0.5"
            />
            <p
              className="text-[10px] leading-relaxed"
              style={{ color: "var(--text-muted)" }}
            >
              False reports may affect your account. Only report content that
              genuinely violates our guidelines.
            </p>
          </div>

          <button
            onClick={handleReport}
            disabled={!reportMsg.trim() || submitting}
            className="w-full h-12 rounded-xl text-sm font-black text-[#ffffff] transition-all active:scale-[0.98] disabled:opacity-30 flex items-center justify-center gap-2"
            style={{
              background: "linear-gradient(135deg,#f43f5e,#dc2626)",
              boxShadow: reportMsg.trim()
                ? "0 4px 22px rgba(244,63,94,0.3)"
                : "none",
            }}
          >
            {submitting ? (
              <Loader2 size={16} className="animate-spin" />
            ) : (
              <Flag size={15} strokeWidth={2.5} />
            )}
            {submitting ? t("report_submitting") : t("report_submit")}
          </button>
        </div>

        {toast && <Toast msg={toast.msg} ok={toast.ok} />}
      </Sheet>
    );
  }

  return null;
}
