"use client";

import React, { useState } from "react";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { TrialPaymentScreenDefinition } from "@/lib/funnel/types";
import { TextInput } from "@/components/ui/TextInput/TextInput";
import { TextAreaInput } from "@/components/ui/TextAreaInput/TextAreaInput";
import { Button } from "@/components/ui/button";
import { Trash, ChevronDown, ChevronRight } from "lucide-react";

interface TrialPaymentScreenConfigProps {
  screen: BuilderScreen & { template: "trialPayment" };
  onUpdate: (updates: Partial<TrialPaymentScreenDefinition>) => void;
}

function CollapsibleSection({
  title,
  children,
  defaultExpanded = false,
}: {
  title: string;
  children: React.ReactNode;
  defaultExpanded?: boolean;
}) {
  const storageKey = `trial-payment-section-${title.toLowerCase().replace(/\s+/g, '-')}`;
  
  const [isExpanded, setIsExpanded] = useState(() => {
    if (typeof window === 'undefined') return defaultExpanded;
    
    const stored = sessionStorage.getItem(storageKey);
    return stored !== null ? JSON.parse(stored) : defaultExpanded;
  });

  const handleToggle = () => {
    const newExpanded = !isExpanded;
    setIsExpanded(newExpanded);
    
    if (typeof window !== 'undefined') {
      sessionStorage.setItem(storageKey, JSON.stringify(newExpanded));
    }
  };

  return (
    <div className="space-y-3">
      <button
        type="button"
        onClick={handleToggle}
        className="flex w-full items-center gap-2 text-left text-sm font-medium text-foreground hover:text-primary transition-colors"
      >
        {isExpanded ? (
          <ChevronDown className="h-4 w-4" />
        ) : (
          <ChevronRight className="h-4 w-4" />
        )}
        {title}
      </button>
      {isExpanded && <div className="space-y-3">{children}</div>}
    </div>
  );
}

export function TrialPaymentScreenConfig({ screen, onUpdate }: TrialPaymentScreenConfigProps) {
  const updateHeaderBlock = (updates: Partial<NonNullable<TrialPaymentScreenDefinition["headerBlock"]>>) => {
    onUpdate({ headerBlock: { ...screen.headerBlock, ...updates } });
  };

  const updateUnlock = (
    updates: Partial<NonNullable<TrialPaymentScreenDefinition["unlockYourSketch"]>>
  ) => {
    onUpdate({ unlockYourSketch: { ...screen.unlockYourSketch, ...updates } });
  };

  const updatePaymentButtons = (
    index: number,
    field: "text" | "icon" | "primary",
    value: string | boolean
  ) => {
    const current = screen.paymentButtons?.buttons ?? [];
    const buttons = current.map((b, i) =>
      i === index
        ? {
            ...b,
            ...(field === "text" ? { text: String(value) } : {}),
            ...(field === "icon" ? { icon: String(value) as "pay" | "google" | "card" } : {}),
            ...(field === "primary" ? { primary: Boolean(value) } : {}),
          }
        : b
    );
    onUpdate({ paymentButtons: { buttons } });
  };

  const updateFooterContacts = (
    field: "email" | "address" | "title",
    value: { href: string; text: string } | { text: string }
  ) => {
    const next = { ...(screen.footer?.contacts ?? {}) } as NonNullable<TrialPaymentScreenDefinition["footer"]>["contacts"];
    if (field === "email") next!.email = value as { href: string; text: string };
    if (field === "address") next!.address = value as { text: string };
    if (field === "title") next!.title = { text: (value as { text: string }).text };
    onUpdate({ footer: { ...screen.footer, contacts: next } });
  };

  return (
    <div className="space-y-4">
      {/* Header Block */}
      <CollapsibleSection title="Header Block" defaultExpanded={true}>
        <div className="space-y-3">
          <TextInput
            label="Текст"
            value={screen.headerBlock?.text?.text ?? ""}
            onChange={(e) => updateHeaderBlock({ text: { ...(screen.headerBlock?.text ?? {}), text: e.target.value } })}
          />
          <TextInput
            label="Таймер (сек)"
            type="number"
            value={String(screen.headerBlock?.timerSeconds ?? 600)}
            onChange={(e) => updateHeaderBlock({ timerSeconds: Number(e.target.value) })}
          />
        </div>
      </CollapsibleSection>

      {/* Unlock Your Sketch */}
      <CollapsibleSection title="Unlock Your Sketch" defaultExpanded={true}>
        <div className="space-y-3">
          <TextInput label="Заголовок" value={screen.unlockYourSketch?.title?.text ?? ""} onChange={(e) => updateUnlock({ title: { text: e.target.value } })} />
          <TextInput label="Подзаголовок" value={screen.unlockYourSketch?.subtitle?.text ?? ""} onChange={(e) => updateUnlock({ subtitle: { text: e.target.value } })} />
          <TextInput label="Изображение" value={screen.unlockYourSketch?.image?.src ?? ""} onChange={(e) => updateUnlock({ image: { src: e.target.value } })} />
          <TextInput label="Текст на блюре" value={screen.unlockYourSketch?.blur?.text?.text ?? ""} onChange={(e) => updateUnlock({ blur: { ...(screen.unlockYourSketch?.blur ?? {}), text: { text: e.target.value }, icon: "lock" } as NonNullable<TrialPaymentScreenDefinition["unlockYourSketch"]>["blur"] })} />
          <TextInput label="Текст кнопки" value={screen.unlockYourSketch?.buttonText ?? ""} onChange={(e) => updateUnlock({ buttonText: e.target.value })} />
        </div>
      </CollapsibleSection>

      {/* Social Proof */}
      <CollapsibleSection title="Social Proof">
        <div className="space-y-3">
          <TextInput
            label="Joined Today - Count"
            value={screen.joinedToday?.count?.text ?? ""}
            onChange={(e) => onUpdate({ joinedToday: { ...screen.joinedToday, count: { text: e.target.value } } })}
          />
          <TextInput
            label="Joined Today - Text"
            value={screen.joinedToday?.text?.text ?? ""}
            onChange={(e) => onUpdate({ joinedToday: { ...screen.joinedToday, text: { text: e.target.value } } })}
          />
          <TextInput
            label="Trusted By Over"
            value={screen.trustedByOver?.text?.text ?? ""}
            onChange={(e) => onUpdate({ trustedByOver: { text: { text: e.target.value } } })}
          />
        </div>
      </CollapsibleSection>

      {/* Finding The One Guide */}
      <CollapsibleSection title="Finding The One Guide">
        <div className="space-y-3">
          <TextInput
            label="Emoji"
            value={screen.findingOneGuide?.header?.emoji?.text ?? ""}
            onChange={(e) => onUpdate({ findingOneGuide: { ...screen.findingOneGuide, header: { ...(screen.findingOneGuide?.header ?? {}), emoji: { text: e.target.value } } } })}
          />
          <TextInput
            label="Title"
            value={screen.findingOneGuide?.header?.title?.text ?? ""}
            onChange={(e) => onUpdate({ findingOneGuide: { ...screen.findingOneGuide, header: { ...(screen.findingOneGuide?.header ?? {}), title: { text: e.target.value } } } })}
          />
          <TextAreaInput
            label="Text"
            rows={4}
            value={screen.findingOneGuide?.text?.text ?? ""}
            onChange={(e) => onUpdate({ findingOneGuide: { ...screen.findingOneGuide, text: { text: e.target.value } } })}
          />
          <TextInput
            label="Blur text"
            value={screen.findingOneGuide?.blur?.text?.text ?? ""}
            onChange={(e) => onUpdate({ findingOneGuide: { ...screen.findingOneGuide, blur: { ...(screen.findingOneGuide?.blur ?? {}), text: { text: e.target.value }, icon: "lock" } } })}
          />
        </div>
      </CollapsibleSection>

      {/* Try For Days */}
      <CollapsibleSection title="Try For Days">
        <div className="space-y-3">
          <TextInput
            label="Title"
            value={screen.tryForDays?.title?.text ?? ""}
            onChange={(e) => onUpdate({ tryForDays: { ...screen.tryForDays, title: { text: e.target.value } } })}
          />
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Items</span>
              <Button
                type="button"
                className="h-7 px-2 text-xs"
                onClick={() => {
                  const current = screen.tryForDays?.textList?.items ?? [];
                  const items = [...current, { text: "" }];
                  onUpdate({ tryForDays: { ...screen.tryForDays, textList: { items } } });
                }}
              >
                Добавить
              </Button>
            </div>
            {(screen.tryForDays?.textList?.items ?? []).map((it, idx) => (
              <div key={idx} className="space-y-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextAreaInput
                  label={`Item #${idx + 1}`}
                  rows={2}
                  value={it.text}
                  onChange={(e) => {
                    const current = screen.tryForDays?.textList?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, text: e.target.value } : v));
                    onUpdate({ tryForDays: { ...screen.tryForDays, textList: { items } } });
                  }}
                />
                <div className="flex justify-end">
                  <Button
                    type="button"
                    variant="ghost"
                    className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                    onClick={() => {
                      const current = screen.tryForDays?.textList?.items ?? [];
                      const items = current.filter((_, i) => i !== idx);
                      onUpdate({ tryForDays: { ...screen.tryForDays, textList: { items } } });
                    }}
                    aria-label="Удалить элемент"
                  >
                    <Trash className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* Pricing & Payment */}
      <CollapsibleSection title="Pricing & Payment">
        <div className="space-y-3">
          <TextInput
            label="Coupon title"
            value={screen.totalPrice?.couponContainer?.title?.text ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: { ...(screen.totalPrice?.couponContainer ?? {}), title: { text: e.target.value } }, priceContainer: screen.totalPrice?.priceContainer } })}
          />
          <TextInput
            label="Coupon button text"
            value={screen.totalPrice?.couponContainer?.buttonText ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: { ...(screen.totalPrice?.couponContainer ?? {}), buttonText: e.target.value }, priceContainer: screen.totalPrice?.priceContainer } })}
          />
          <TextInput
            label="Price title"
            value={screen.totalPrice?.priceContainer?.title?.text ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: screen.totalPrice?.couponContainer ?? { title: { text: "" }, buttonText: "" }, priceContainer: { ...(screen.totalPrice?.priceContainer ?? {}), title: { text: e.target.value } } } })}
          />
          <TextInput
            label="Price"
            value={screen.totalPrice?.priceContainer?.price?.text ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: screen.totalPrice?.couponContainer ?? { title: { text: "" }, buttonText: "" }, priceContainer: { ...(screen.totalPrice?.priceContainer ?? {}), price: { text: e.target.value } } } })}
          />
          <TextInput
            label="Old price"
            value={screen.totalPrice?.priceContainer?.oldPrice?.text ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: screen.totalPrice?.couponContainer ?? { title: { text: "" }, buttonText: "" }, priceContainer: { ...(screen.totalPrice?.priceContainer ?? {}), oldPrice: { text: e.target.value } } } })}
          />
          <TextInput
            label="Discount"
            value={screen.totalPrice?.priceContainer?.discount?.text ?? ""}
            onChange={(e) => onUpdate({ totalPrice: { couponContainer: screen.totalPrice?.couponContainer ?? { title: { text: "" }, buttonText: "" }, priceContainer: { ...(screen.totalPrice?.priceContainer ?? {}), discount: { text: e.target.value } } } })}
          />
          
          <div className="pt-3 border-t border-border/30">
            <span className="text-xs font-medium text-muted-foreground mb-2 block">Payment Buttons</span>
            {(screen.paymentButtons?.buttons ?? []).map((b, i) => (
              <div key={i} className="space-y-2 mb-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextInput label={`Текст #${i + 1}`} value={b.text} onChange={(e) => updatePaymentButtons(i, "text", e.target.value)} />
                <TextInput label="Иконка (pay|google|card)" value={("icon" in b ? (b as { icon?: "pay"|"google"|"card" }).icon ?? "" : "")} onChange={(e) => updatePaymentButtons(i, "icon", e.target.value)} />
                <label className="text-xs flex items-center gap-2"><input type="checkbox" checked={("primary" in b ? (b as { primary?: boolean }).primary ?? false : false)} onChange={(e) => updatePaymentButtons(i, "primary", e.target.checked)} /> Primary</label>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* Trust & Guarantees */}
      <CollapsibleSection title="Trust & Guarantees">
        <div className="space-y-3">
          <TextInput
            label="Money Back Guarantee - Title"
            value={screen.moneyBackGuarantee?.title?.text ?? ""}
            onChange={(e) => onUpdate({ moneyBackGuarantee: { ...screen.moneyBackGuarantee, title: { text: e.target.value } } })}
          />
          <TextAreaInput
            label="Money Back Guarantee - Text"
            rows={2}
            value={screen.moneyBackGuarantee?.text?.text ?? ""}
            onChange={(e) => onUpdate({ moneyBackGuarantee: { ...screen.moneyBackGuarantee, text: { text: e.target.value } } })}
          />
          <TextAreaInput
            label="Policy Text"
            rows={3}
            value={screen.policy?.text?.text ?? ""}
            onChange={(e) => onUpdate({ policy: { text: { text: e.target.value } } })}
          />
        </div>
      </CollapsibleSection>

      {/* Reviews */}
      <CollapsibleSection title="Reviews">
        <div className="space-y-3">
          <TextInput
            label="Title"
            value={screen.reviews?.title?.text ?? ""}
            onChange={(e) => onUpdate({ reviews: { title: { text: e.target.value }, items: screen.reviews?.items ?? [] } })}
          />
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Items</span>
              <Button
                type="button"
                className="h-7 px-2 text-xs"
                onClick={() => {
                  const current = screen.reviews?.items ?? [];
                  const items = [
                    ...current,
                    { name: { text: "" }, text: { text: "" }, rating: 5 },
                  ];
                  onUpdate({ reviews: { ...screen.reviews, items } });
                }}
              >
                Добавить
              </Button>
            </div>
            {(screen.reviews?.items ?? []).map((r, idx) => (
              <div key={idx} className="space-y-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextInput
                  label={`Review #${idx + 1} name`}
                  value={r.name.text}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, name: { text: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <TextInput
                  label="Date"
                  value={r.date?.text ?? ""}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, date: { text: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <TextAreaInput
                  label="Text (supports **bold**)"
                  rows={3}
                  value={r.text.text}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, text: { text: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <TextInput
                  label="Avatar src"
                  value={r.avatar?.src ?? ""}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, avatar: { src: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <TextInput
                  label="Portrait src"
                  value={r.portrait?.src ?? ""}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, portrait: { src: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <TextInput
                  label="Photo src"
                  value={r.photo?.src ?? ""}
                  onChange={(e) => {
                    const current = screen.reviews?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, photo: { src: e.target.value } } : v));
                    onUpdate({ reviews: { ...screen.reviews, items } });
                  }}
                />
                <div className="space-y-2">
                  <TextInput
                    label="Rating (1-5)"
                    type="number"
                    value={String(r.rating ?? 5)}
                    onChange={(e) => {
                      const current = screen.reviews?.items ?? [];
                      const items = current.map((v, i) => (i === idx ? { ...v, rating: Number(e.target.value) } : v));
                      onUpdate({ reviews: { ...screen.reviews, items } });
                    }}
                  />
                  <div className="flex justify-end">
                    <Button
                      type="button"
                      variant="ghost"
                      className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                      onClick={() => {
                        const current = screen.reviews?.items ?? [];
                        const items = current.filter((_, i) => i !== idx);
                        onUpdate({ reviews: { ...screen.reviews, items } });
                      }}
                      aria-label="Удалить отзыв"
                    >
                      <Trash className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* Common Questions */}
      <CollapsibleSection title="Common Questions">
        <div className="space-y-3">
          <TextInput
            label="Title"
            value={screen.commonQuestions?.title?.text ?? ""}
            onChange={(e) => onUpdate({ commonQuestions: { title: { text: e.target.value }, items: screen.commonQuestions?.items ?? [] } })}
          />
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Items</span>
              <Button
                type="button"
                className="h-7 px-2 text-xs"
                onClick={() => {
                  const current = screen.commonQuestions?.items ?? [];
                  const items = [...current, { question: "", answer: "" }];
                  onUpdate({ commonQuestions: { ...screen.commonQuestions, items } });
                }}
              >
                Добавить
              </Button>
            </div>
            {(screen.commonQuestions?.items ?? []).map((q, idx) => (
              <div key={idx} className="grid grid-cols-1 gap-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextInput
                  label={`Question #${idx + 1}`}
                  value={q.question}
                  onChange={(e) => {
                    const current = screen.commonQuestions?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, question: e.target.value } : v));
                    onUpdate({ commonQuestions: { ...screen.commonQuestions, items } });
                  }}
                />
                <TextAreaInput
                  label="Answer"
                  rows={2}
                  value={q.answer}
                  onChange={(e) => {
                    const current = screen.commonQuestions?.items ?? [];
                    const items = current.map((v, i) => (i === idx ? { ...v, answer: e.target.value } : v));
                    onUpdate({ commonQuestions: { ...screen.commonQuestions, items } });
                  }}
                />
                <div className="flex items-center justify-end">
                  <Button
                    type="button"
                    variant="ghost"
                    className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                    onClick={() => {
                      const current = screen.commonQuestions?.items ?? [];
                      const items = current.filter((_, i) => i !== idx);
                      onUpdate({ commonQuestions: { ...screen.commonQuestions, items } });
                    }}
                    aria-label="Удалить вопрос"
                  >
                    <Trash className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* Progress & Steps */}
      <CollapsibleSection title="Progress To See Soulmate">
        <div className="space-y-3">
          <TextInput
            label="Title"
            value={screen.progressToSeeSoulmate?.title?.text ?? ""}
            onChange={(e) => onUpdate({ progressToSeeSoulmate: { ...screen.progressToSeeSoulmate, title: { text: e.target.value } } })}
          />
          <TextInput
            label="Progress value (0-100)"
            type="number"
            value={String(screen.progressToSeeSoulmate?.progress?.value ?? 0)}
            onChange={(e) => onUpdate({ progressToSeeSoulmate: { ...screen.progressToSeeSoulmate, progress: { value: Number(e.target.value) } } })}
          />
          <TextInput
            label="Left text"
            value={screen.progressToSeeSoulmate?.leftText?.text ?? ""}
            onChange={(e) => onUpdate({ progressToSeeSoulmate: { ...screen.progressToSeeSoulmate, leftText: { text: e.target.value } } })}
          />
          <TextInput
            label="Right text"
            value={screen.progressToSeeSoulmate?.rightText?.text ?? ""}
            onChange={(e) => onUpdate({ progressToSeeSoulmate: { ...screen.progressToSeeSoulmate, rightText: { text: e.target.value } } })}
          />
        </div>
      </CollapsibleSection>

      {/* Steps To See Soulmate */}
      <CollapsibleSection title="Steps To See Soulmate">
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs text-muted-foreground">Steps</span>
            <Button
              type="button"
              className="h-7 px-2 text-xs"
              onClick={() => {
                const current = screen.stepsToSeeSoulmate?.steps ?? [];
                const steps = [
                  ...current,
                  { title: { text: "" }, description: { text: "" }, icon: "questions" as const, isActive: false },
                ];
                onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
              }}
            >
              Добавить шаг
            </Button>
          </div>

          {(screen.stepsToSeeSoulmate?.steps ?? []).map((step, idx) => (
            <div key={idx} className="grid grid-cols-1 gap-2 border border-border/50 rounded-lg bg-muted/5 p-3">
              <div className="space-y-3">
                <TextInput
                  label={`Step #${idx + 1} title`}
                  value={step.title.text}
                  onChange={(e) => {
                    const current = screen.stepsToSeeSoulmate?.steps ?? [];
                    const steps = current.map((s, i) => (i === idx ? { ...s, title: { text: e.target.value } } : s));
                    onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
                  }}
                />
                <TextInput
                  label="Icon (questions|profile|sketch|astro|chat)"
                  value={(step.icon ?? "") as string}
                  onChange={(e) => {
                    const icon = e.target.value as "questions" | "profile" | "sketch" | "astro" | "chat";
                    const current = screen.stepsToSeeSoulmate?.steps ?? [];
                    const steps = current.map((s, i) => (i === idx ? { ...s, icon } : s));
                    onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
                  }}
                />
              </div>
              <TextAreaInput
                label="Description"
                rows={2}
                value={step.description.text}
                onChange={(e) => {
                  const current = screen.stepsToSeeSoulmate?.steps ?? [];
                  const steps = current.map((s, i) => (i === idx ? { ...s, description: { text: e.target.value } } : s));
                  onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
                }}
              />
              <div className="flex items-center justify-between">
                <label className="text-xs flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={Boolean(step.isActive)}
                    onChange={(e) => {
                      const current = screen.stepsToSeeSoulmate?.steps ?? [];
                      const steps = current.map((s, i) => (i === idx ? { ...s, isActive: e.target.checked } : s));
                      onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
                    }}
                  />
                  Active
                </label>
                <Button
                  type="button"
                  variant="ghost"
                  className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                  onClick={() => {
                    const current = screen.stepsToSeeSoulmate?.steps ?? [];
                    const steps = current.filter((_, i) => i !== idx);
                    onUpdate({ stepsToSeeSoulmate: { ...screen.stepsToSeeSoulmate, steps } });
                  }}
                  aria-label="Удалить шаг"
                >
                  <Trash className="h-4 w-4" />
                </Button>
              </div>
            </div>
          ))}
        </div>
      </CollapsibleSection>

      {/* Users' Portraits */}
      <CollapsibleSection title="Users' Portraits">
        <div className="space-y-3">
          <TextInput
            label="Title"
            value={screen.usersPortraits?.title?.text ?? ""}
            onChange={(e) => onUpdate({ usersPortraits: { ...screen.usersPortraits, title: { text: e.target.value } } })}
          />
          <TextInput
            label="Button text"
            value={screen.usersPortraits?.buttonText ?? ""}
            onChange={(e) => onUpdate({ usersPortraits: { ...screen.usersPortraits, buttonText: e.target.value } })}
          />
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Images</span>
              <Button
                type="button"
                className="h-7 px-2 text-xs"
                onClick={() => {
                  const current = screen.usersPortraits?.images ?? [];
                  const images = [...current, { src: "" }];
                  onUpdate({ usersPortraits: { ...screen.usersPortraits, images } });
                }}
              >
                Добавить
              </Button>
            </div>
            {(screen.usersPortraits?.images ?? []).map((img, idx) => (
              <div key={idx} className="space-y-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextInput
                  label={`Image #${idx + 1} src`}
                  value={img.src}
                  onChange={(e) => {
                    const current = screen.usersPortraits?.images ?? [];
                    const images = current.map((v, i) => (i === idx ? { ...v, src: e.target.value } : v));
                    onUpdate({ usersPortraits: { ...screen.usersPortraits, images } });
                  }}
                />
                <div className="flex justify-end">
                  <Button
                    type="button"
                    variant="ghost"
                    className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                    onClick={() => {
                      const current = screen.usersPortraits?.images ?? [];
                      const images = current.filter((_, i) => i !== idx);
                      onUpdate({ usersPortraits: { ...screen.usersPortraits, images } });
                    }}
                    aria-label="Удалить изображение"
                  >
                    <Trash className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* Joined Today With Avatars */}
      <CollapsibleSection title="Joined Today With Avatars">
        <div className="space-y-3">
          <TextInput
            label="Count"
            value={screen.joinedTodayWithAvatars?.count?.text ?? ""}
            onChange={(e) => onUpdate({ joinedTodayWithAvatars: { ...screen.joinedTodayWithAvatars, count: { text: e.target.value } } })}
          />
          <TextInput
            label="Text"
            value={screen.joinedTodayWithAvatars?.text?.text ?? ""}
            onChange={(e) => onUpdate({ joinedTodayWithAvatars: { ...screen.joinedTodayWithAvatars, text: { text: e.target.value } } })}
          />
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Avatars</span>
              <Button
                type="button"
                className="h-7 px-2 text-xs"
                onClick={() => {
                  const current = screen.joinedTodayWithAvatars?.avatars?.images ?? [];
                  const images = [...current, { src: "" }];
                  onUpdate({ joinedTodayWithAvatars: { ...screen.joinedTodayWithAvatars, avatars: { images } } });
                }}
              >
                Добавить
              </Button>
            </div>
            {(screen.joinedTodayWithAvatars?.avatars?.images ?? []).map((img, idx) => (
              <div key={idx} className="space-y-2 border border-border/50 rounded-lg bg-muted/5 p-3">
                <TextInput
                  label={`Avatar #${idx + 1} src`}
                  value={img.src}
                  onChange={(e) => {
                    const current = screen.joinedTodayWithAvatars?.avatars?.images ?? [];
                    const images = current.map((v, i) => (i === idx ? { ...v, src: e.target.value } : v));
                    onUpdate({ joinedTodayWithAvatars: { ...screen.joinedTodayWithAvatars, avatars: { images } } });
                  }}
                />
                <div className="flex justify-end">
                  <Button
                    type="button"
                    variant="ghost"
                    className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                    onClick={() => {
                      const current = screen.joinedTodayWithAvatars?.avatars?.images ?? [];
                      const images = current.filter((_, i) => i !== idx);
                      onUpdate({ joinedTodayWithAvatars: { ...screen.joinedTodayWithAvatars, avatars: { images } } });
                    }}
                    aria-label="Удалить аватар"
                  >
                    <Trash className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* FAQ & Support */}
      <CollapsibleSection title="FAQ & Support">
        <div className="space-y-3">
          <TextInput
            label="Still Have Questions - Title"
            value={screen.stillHaveQuestions?.title?.text ?? ""}
            onChange={(e) => onUpdate({ stillHaveQuestions: { ...screen.stillHaveQuestions, title: { text: e.target.value } } })}
          />
          <TextInput
            label="Action button text"
            value={screen.stillHaveQuestions?.actionButtonText ?? ""}
            onChange={(e) => onUpdate({ stillHaveQuestions: { ...screen.stillHaveQuestions, actionButtonText: e.target.value } })}
          />
          <TextInput
            label="Contact button text"
            value={screen.stillHaveQuestions?.contactButtonText ?? ""}
            onChange={(e) => onUpdate({ stillHaveQuestions: { ...screen.stillHaveQuestions, contactButtonText: e.target.value } })}
          />
        </div>
      </CollapsibleSection>

      {/* Footer */}
      <CollapsibleSection title="Footer">
        <div className="space-y-3">
          <TextInput
            label="Email"
            value={screen.footer?.contacts?.email?.text ?? screen.footer?.contacts?.email?.href ?? ""}
            onChange={(e) => updateFooterContacts("email", { href: e.target.value, text: e.target.value })}
          />
          <TextAreaInput
            label="Address"
            rows={2}
            value={screen.footer?.contacts?.address?.text ?? ""}
            onChange={(e) => updateFooterContacts("address", { text: e.target.value })}
          />
        </div>
      </CollapsibleSection>
    </div>
  );
}
