import { useEffect, useMemo, useState } from 'react';
import {
  Alert,
  Button,
  Card,
  Col,
  Divider,
  Empty,
  Form,
  Input,
  List,
  Row,
  Select,
  Segmented,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { FileTextOutlined, PictureOutlined, ReloadOutlined, ThunderboltOutlined, VideoCameraOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { request } from '@/request';
import { selectCurrentAdmin } from '@/redux/auth/selectors';
import { canAccessPermission } from '@/utils/permissions';
import GrowthWorkspaceShell from './GrowthWorkspaceShell';
import {
  CHANNEL_OPTIONS,
  CONTENT_TYPE_OPTIONS,
  buildAiBriefPayload,
  buildAudienceSummary,
  createHandoffState,
} from './growthWorkspace';

const STEP_ITEMS = [
  { title: 'Brief', description: 'Set campaign and brand context' },
  { title: 'Generate', description: 'Draft AI content' },
  { title: 'Variants', description: 'Compare and edit outputs' },
  { title: 'Brand Assets', description: 'Generate visual support' },
  { title: 'Publish / Handoff', description: 'Send work into campaigns or automations' },
];

const MODE_CONFIG = {
  content: {
    label: 'Content',
    icon: <FileTextOutlined />,
    defaultType: 'newsletter',
    accent: '#1677ff',
    helper: 'Generate newsletters, emails, blog posts, captions, and campaign copy with editable variants.',
  },
  flyer: {
    label: 'Flyer',
    icon: <PictureOutlined />,
    defaultType: 'flyer',
    accent: '#722ed1',
    helper: 'Create flyer copy, layout direction, and a Fal.ai-ready visual prompt from the same brief.',
  },
  video: {
    label: 'Video',
    icon: <VideoCameraOutlined />,
    defaultType: 'video_script',
    accent: '#fa541c',
    helper: 'Plan short-form videos with hooks, scenes, captions, voiceover, CTA, and storyboard notes.',
  },
};

const MODE_OPTIONS = Object.entries(MODE_CONFIG).map(([value, item]) => ({
  value,
  label: (
    <Space size={6}>
      {item.icon}
      {item.label}
    </Space>
  ),
}));

const QUICK_BRIEFS = [
  {
    key: 'newsletter',
    label: 'Newsletter',
    mode: 'content',
    values: {
      generationMode: 'content',
      type: 'newsletter',
      channel: 'email',
      goal: 'Nurture warm leads into booked consultations',
      audience: 'Warm leads and recent website visitors',
      brandVoice: 'Helpful, confident, practical',
      cta: 'Book a consultation',
      prompt: 'Create a newsletter that educates the audience, introduces the offer, and ends with one clear CTA.',
    },
  },
  {
    key: 'sale-flyer',
    label: 'Sales Flyer',
    mode: 'flyer',
    values: {
      generationMode: 'flyer',
      type: 'flyer',
      channel: 'instagram',
      goal: 'Announce a limited-time offer and drive inquiries',
      audience: 'Retail buyers who respond to clear value and urgency',
      brandVoice: 'Bold, trustworthy, concise',
      cta: 'Send a WhatsApp message today',
      flyerSize: '1080x1350',
      visualStyle: 'Clean premium product-led layout',
      prompt: 'Create a high-converting flyer with a strong headline, benefit-led copy, price/offer block, CTA, and visual direction.',
    },
  },
  {
    key: 'reel',
    label: '30s Reel',
    mode: 'video',
    values: {
      generationMode: 'video',
      type: 'video_script',
      channel: 'instagram',
      goal: 'Create awareness and drive profile visits',
      audience: 'Prospects comparing providers',
      brandVoice: 'Energetic, clear, credible',
      cta: 'Follow for more and message us to get started',
      videoFormat: 'vertical_reel',
      videoDuration: '30',
      sceneCount: 5,
      prompt: 'Create a 30-second reel with a strong first-three-seconds hook, five scenes, captions, voiceover, and production notes.',
    },
  },
];

const FLYER_SIZE_OPTIONS = [
  { value: '1080x1080', label: 'Square Post - 1080 x 1080' },
  { value: '1080x1350', label: 'Portrait Post - 1080 x 1350' },
  { value: '1080x1920', label: 'Story/Reel Cover - 1080 x 1920' },
  { value: 'A4', label: 'A4 Print Flyer' },
];

const VIDEO_FORMAT_OPTIONS = [
  { value: 'vertical_reel', label: 'Vertical Reel / Short' },
  { value: 'story_ad', label: 'Story Ad' },
  { value: 'landscape_ad', label: 'Landscape Ad' },
  { value: 'explainer', label: 'Explainer Video' },
];

const VISUAL_STYLE_OPTIONS = [
  { value: 'Clean premium product-led layout', label: 'Premium Product' },
  { value: 'Bold retail promo with large price block', label: 'Retail Promo' },
  { value: 'Minimal corporate announcement', label: 'Corporate' },
  { value: 'Bright social-first lifestyle creative', label: 'Lifestyle Social' },
];

const normalizeModeFromType = (type) => {
  if (['flyer', 'flyer_copy'].includes(type)) return 'flyer';
  if (['video_script', 'storyboard', 'script'].includes(type)) return 'video';
  return 'content';
};

const buildProductionPrompt = (values = {}, mode = 'content', variantInstruction = '') => {
  const lines = [
    values.prompt,
    '',
    `Output mode: ${MODE_CONFIG[mode]?.label || 'Content'}.`,
    `Goal: ${values.goal || 'Not specified'}.`,
    `Channel: ${values.channel || 'Not specified'}.`,
    `Audience: ${values.audience || 'Not specified'}.`,
    `Brand voice: ${values.brandVoice || 'Not specified'}.`,
    `CTA: ${values.cta || 'Not specified'}.`,
    `Offer/product context: ${values.offerContext || 'Not specified'}.`,
  ];

  if (mode === 'flyer') {
    lines.push(
      `Flyer format: ${values.flyerSize || '1080x1080'}.`,
      `Visual style: ${values.visualStyle || 'Clean premium product-led layout'}.`,
      `Required sections: headline, subhead, body copy, CTA, layout hierarchy, color/imagery notes, Fal.ai image prompt.`
    );
  }

  if (mode === 'video') {
    lines.push(
      `Video format: ${values.videoFormat || 'vertical_reel'}.`,
      `Duration: ${values.videoDuration || '30'} seconds.`,
      `Scene count: ${values.sceneCount || 5}.`,
      `Required sections: hook, scene-by-scene storyboard, voiceover, on-screen captions, shot direction, music/mood, CTA.`
    );
  }

  if (variantInstruction) lines.push('', variantInstruction);
  return lines.filter(Boolean).join('\n');
};

const splitStoryboard = (content = '') => {
  const sections = content
    .split(/\n(?=(scene|shot|frame|beat)\s*\d*[:.-]?)/i)
    .map((item) => item.trim())
    .filter(Boolean);

  if (sections.length > 1) return sections.slice(0, 6);
  return content
    .split('\n')
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 6);
};

export default function AIStudio() {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  const [campaigns, setCampaigns] = useState([]);
  const [segments, setSegments] = useState([]);
  const [assets, setAssets] = useState([]);
  const [variants, setVariants] = useState([]);
  const [selectedVariant, setSelectedVariant] = useState(0);
  const [brandAsset, setBrandAsset] = useState(null);
  const [loading, setLoading] = useState(false);
  const [assetTypeFilter, setAssetTypeFilter] = useState();
  const [providerFilter, setProviderFilter] = useState();
  const navigate = useNavigate();
  const location = useLocation();
  const currentAdmin = useSelector(selectCurrentAdmin);
  const canGenerate = canAccessPermission(currentAdmin, 'ai.studio.create');
  const handoff = location.state?.handoff;

  const briefValues = Form.useWatch([], form) || {};
  const generationMode = briefValues.generationMode || normalizeModeFromType(briefValues.type);
  const modeConfig = MODE_CONFIG[generationMode] || MODE_CONFIG.content;

  const load = async () => {
    setLoading(true);
    const [campaignResponse, segmentResponse, assetResponse] = await Promise.all([
      request.list({ entity: 'campaign', options: { page: 1, items: 100 } }),
      request.list({ entity: 'audiencesegment', options: { page: 1, items: 100 } }),
      request.get({ entity: 'ai/workspace/assets?limit=20' }),
    ]);
    setCampaigns(campaignResponse?.result || []);
    setSegments(segmentResponse?.result || []);
    setAssets(assetResponse?.result || []);
    setLoading(false);
  };

  useEffect(() => {
    load();
  }, []);

  useEffect(() => {
    if (location.pathname.endsWith('/assets')) {
      setCurrentStep(2);
    } else if (location.pathname.endsWith('/providers')) {
      setCurrentStep(4);
    } else if (!handoff) {
      setCurrentStep(0);
    }
  }, [handoff, location.pathname]);

  useEffect(() => {
    if (!handoff) return;
    form.setFieldsValue({
      generationMode: normalizeModeFromType(handoff.asset?.type),
      brandName: handoff.campaign?.name || handoff.asset?.brandContext?.brandName || '',
      linkedCampaignId: handoff.campaign?._id,
      linkedSegmentId: handoff.segment?._id,
      prompt: handoff.content || handoff.asset?.content || '',
      type: handoff.asset?.type || 'email',
      audience: handoff.segment?.name,
    });
  }, [handoff, form]);

  const selectedSegment = useMemo(
    () => segments.find((segment) => segment._id === briefValues.linkedSegmentId),
    [segments, briefValues.linkedSegmentId]
  );
  const selectedCampaign = useMemo(
    () => campaigns.find((campaign) => campaign._id === briefValues.linkedCampaignId),
    [campaigns, briefValues.linkedCampaignId]
  );
  const activeVariant = variants[selectedVariant];

  const generateVariants = async () => {
    await form.validateFields([
      'generationMode',
      'brandName',
      'type',
      'prompt',
      'goal',
      'channel',
      'audience',
      'brandVoice',
      'cta',
      'offerContext',
    ]);
    const values = form.getFieldsValue(true);
    const mode = values.generationMode || normalizeModeFromType(values.type);
    const contentType = values.type || MODE_CONFIG[mode]?.defaultType || 'email';
    const prompt = buildProductionPrompt(values, mode, 'Create a polished primary version that is ready for review.');
    const payload = buildAiBriefPayload({ ...values, type: contentType, prompt });
    const [primary, alternate] = await Promise.all([
      request.post({ entity: 'ai/content/generate', jsonData: payload }),
      request.post({
        entity: 'ai/content/generate',
        jsonData: {
          ...payload,
          prompt: buildProductionPrompt(
            values,
            mode,
            'Create an alternate angle with a different opening, visual hook, and CTA framing.'
          ),
        },
      }),
    ]);
    const nextVariants = [primary, alternate].map((response, index) => ({
      key: `variant-${index + 1}`,
      label: `Variant ${index + 1}`,
      content:
        response?.result?.asset?.content ||
        response?.result?.provider?.content ||
        JSON.stringify(response?.result, null, 2),
      asset: response?.result?.asset || null,
    }));
    setVariants(nextVariants);
    setSelectedVariant(0);
    setCurrentStep(2);
    load();
    message.success(`${MODE_CONFIG[mode]?.label || 'AI'} variants generated`);
  };

  const generateBrandAsset = async () => {
    await form.validateFields(['brandName', 'prompt']);
    const values = form.getFieldsValue(true);
    const mode = values.generationMode || normalizeModeFromType(values.type);
    const response = await request.post({
      entity: 'ai/brand-asset/generate',
      jsonData: {
        prompt: `${buildProductionPrompt(values, mode)}

Create ${mode === 'video' ? 'a hero keyframe and storyboard visual direction' : 'a brand-aligned flyer or campaign visual'}.
Use this format or constraint: ${mode === 'flyer' ? values.flyerSize || '1080x1080' : values.videoFormat || values.channel || 'social'}.
Match this visual brief to the generated campaign copy.`,
        brandContext: {
          brandName: values.brandName,
          generationMode: mode,
          flyerSize: values.flyerSize,
          videoFormat: values.videoFormat,
          campaignId: values.linkedCampaignId,
          audienceSegment: values.linkedSegmentId,
        },
      },
    });
    setBrandAsset(response?.result?.asset || response?.result?.provider || null);
    setCurrentStep(3);
    load();
    message.success('Brand asset request sent');
  };

  const generateProductionPack = async () => {
    await generateVariants();
    await generateBrandAsset();
  };

  const applyQuickBrief = (brief) => {
    form.setFieldsValue(brief.values);
    setCurrentStep(0);
    message.success(`${brief.label} brief loaded`);
  };

  const createSocialDraft = async () => {
    if (!activeVariant?.content) {
      message.warning('Generate a content variant first.');
      return;
    }
    await request.create({
      entity: 'socialpost',
      jsonData: {
        provider: ['facebook', 'instagram'].includes(briefValues.channel) ? briefValues.channel : 'facebook',
        caption: activeVariant.content,
        mediaUrl: brandAsset?.mediaUrl,
        campaign: briefValues.linkedCampaignId,
        status: 'draft',
      },
    });
    message.success('Social post draft created');
  };

  const createProductionTask = async () => {
    if (!activeVariant?.content && !brandAsset) {
      message.warning('Generate a content or visual asset before creating a task.');
      return;
    }
    await request.create({
      entity: 'task',
      jsonData: {
        title: `Review ${modeConfig.label.toLowerCase()} asset`,
        description: `Production mode: ${modeConfig.label}\nLinked campaign: ${selectedCampaign?.name || 'None'}\nLinked audience: ${selectedSegment?.name || 'None'}\n\nSelected output:\n${activeVariant?.content || brandAsset?.content || brandAsset?.message || ''}`.trim(),
        priority: generationMode === 'video' ? 'high' : 'normal',
        status: 'todo',
        relatedTo: {
          entityType: activeVariant?.asset?.type || brandAsset?.type || 'contentasset',
          entityId: activeVariant?.asset?._id || brandAsset?._id,
        },
      },
    });
    message.success('Production task created in Task Management');
  };

  const handoffToMarketing = () => {
    navigate('/marketing', {
      state: {
        handoff: createHandoffState({
          source: 'ai-studio',
          campaign: selectedCampaign,
          asset: activeVariant?.asset || brandAsset,
          segment: selectedSegment,
          content: activeVariant?.content,
        }),
      },
    });
  };

  const handoffToAutomations = () => {
    navigate('/automations', {
      state: {
        handoff: createHandoffState({
          source: 'ai-studio',
          campaign: selectedCampaign,
          asset: activeVariant?.asset || brandAsset,
          segment: selectedSegment,
          content: activeVariant?.content,
        }),
      },
    });
  };

  const filteredAssets = useMemo(() => {
    return assets.filter((asset) => {
      if (assetTypeFilter && asset.type !== assetTypeFilter) return false;
      if (providerFilter && asset.provider !== providerFilter) return false;
      return true;
    });
  }, [assets, assetTypeFilter, providerFilter]);

  const main = (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Card
        title="Production Brief"
        extra={<Tag color={generationMode === 'video' ? 'orange' : generationMode === 'flyer' ? 'purple' : 'blue'}>{modeConfig.label}</Tag>}
      >
        <Space direction="vertical" size={14} style={{ width: '100%' }}>
          <Alert
            type="info"
            showIcon
            message="Choose what you want to produce"
            description={modeConfig.helper}
          />
          <Segmented
            block
            options={MODE_OPTIONS}
            value={generationMode}
            onChange={(value) =>
              form.setFieldsValue({
                generationMode: value,
                type: MODE_CONFIG[value]?.defaultType || 'email',
              })
            }
          />
          <Space wrap>
            <Typography.Text type="secondary">Quick briefs:</Typography.Text>
            {QUICK_BRIEFS.map((brief) => (
              <Button
                key={brief.key}
                size="small"
                icon={<ThunderboltOutlined />}
                onClick={() => applyQuickBrief(brief)}
              >
                {brief.label}
              </Button>
            ))}
          </Space>
        </Space>

        <Divider />

        <Form
          form={form}
          layout="vertical"
          initialValues={{
            generationMode: 'content',
            type: 'newsletter',
            channel: 'email',
            flyerSize: '1080x1080',
            visualStyle: 'Clean premium product-led layout',
            videoFormat: 'vertical_reel',
            videoDuration: '30',
            sceneCount: 5,
          }}
        >
          <Form.Item name="generationMode" hidden>
            <Input />
          </Form.Item>
          <Row gutter={12}>
            <Col xs={24} md={12}>
              <Form.Item name="brandName" label="Brand Name" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="goal" label="Campaign Goal" rules={[{ required: true }]}>
                <Input placeholder="Increase replies, book demos, nurture leads..." />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="channel" label="Primary Channel" rules={[{ required: true }]}>
                <Select options={CHANNEL_OPTIONS} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="type" label="Asset Type" rules={[{ required: true }]}>
                <Select
                  options={
                    generationMode === 'flyer'
                      ? CONTENT_TYPE_OPTIONS.filter((item) => ['flyer', 'flyer_copy'].includes(item.value))
                      : generationMode === 'video'
                        ? CONTENT_TYPE_OPTIONS.filter((item) => ['video_script', 'storyboard', 'script'].includes(item.value))
                        : CONTENT_TYPE_OPTIONS.filter((item) => !['flyer', 'video_script', 'storyboard'].includes(item.value))
                  }
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="audience" label="Audience" rules={[{ required: true }]}>
                <Input placeholder="Warm leads, new customers, dormant buyers..." />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="brandVoice" label="Brand Voice">
                <Input placeholder="Direct, premium, playful..." />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="cta" label="Primary CTA">
                <Input placeholder="Book a demo, reply now, shop today..." />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="offerContext" label="Offer / Product Context">
                <Input placeholder="Starter plan, launch promo, webinar..." />
              </Form.Item>
            </Col>
            {generationMode === 'flyer' && (
              <>
                <Col xs={24} md={12}>
                  <Form.Item name="flyerSize" label="Flyer Format">
                    <Select options={FLYER_SIZE_OPTIONS} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="visualStyle" label="Visual Style">
                    <Select options={VISUAL_STYLE_OPTIONS} />
                  </Form.Item>
                </Col>
              </>
            )}
            {generationMode === 'video' && (
              <>
                <Col xs={24} md={8}>
                  <Form.Item name="videoFormat" label="Video Format">
                    <Select options={VIDEO_FORMAT_OPTIONS} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={8}>
                  <Form.Item name="videoDuration" label="Duration">
                    <Select
                      options={[
                        { value: '15', label: '15 seconds' },
                        { value: '30', label: '30 seconds' },
                        { value: '60', label: '60 seconds' },
                      ]}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} md={8}>
                  <Form.Item name="sceneCount" label="Scene Count">
                    <Select
                      options={[
                        { value: 3, label: '3 scenes' },
                        { value: 5, label: '5 scenes' },
                        { value: 7, label: '7 scenes' },
                      ]}
                    />
                  </Form.Item>
                </Col>
              </>
            )}
            <Col xs={24} md={12}>
              <Form.Item name="linkedCampaignId" label="Linked Campaign">
                <Select allowClear options={campaigns.map((campaign) => ({ value: campaign._id, label: campaign.name }))} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="linkedSegmentId" label="Linked Audience Segment">
                <Select allowClear options={segments.map((segment) => ({ value: segment._id, label: segment.name }))} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="prompt" label="Prompt" rules={[{ required: true }]}>
                <Input.TextArea rows={5} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Space wrap>
          <Button type="primary" disabled={!canGenerate} onClick={generateVariants}>
            Generate {modeConfig.label} Variants
          </Button>
          <Button disabled={!canGenerate} onClick={generateBrandAsset}>
            Generate Visual Asset
          </Button>
          <Button disabled={!canGenerate} icon={<ThunderboltOutlined />} onClick={generateProductionPack}>
            Generate Full Pack
          </Button>
        </Space>
      </Card>

      <Card
        title={`${modeConfig.label} Review`}
        extra={activeVariant?.content ? <Tag color="green">Editable output ready</Tag> : <Tag>Waiting for generation</Tag>}
      >
        <Space direction="vertical" size={12} style={{ width: '100%' }}>
          {variants.length ? (
            <>
              <Space wrap>
                {variants.map((variant, index) => (
                  <Button
                    key={variant.key}
                    type={selectedVariant === index ? 'primary' : 'default'}
                    onClick={() => {
                      setSelectedVariant(index);
                      setCurrentStep(2);
                    }}
                  >
                    {variant.label}
                  </Button>
                ))}
              </Space>
              <Input.TextArea
                rows={generationMode === 'video' ? 12 : 10}
                value={activeVariant?.content || ''}
                onChange={(event) =>
                  setVariants((current) =>
                    current.map((variant, index) =>
                      index === selectedVariant ? { ...variant, content: event.target.value } : variant
                    )
                  )
                }
                placeholder="Generate content to review and edit it here."
              />
              {generationMode === 'flyer' && (
                <Alert
                  type="success"
                  showIcon
                  message="Flyer production checklist"
                  description="Review the headline, CTA, image prompt, layout hierarchy, and offer block before handing this to Marketing or Fal.ai."
                />
              )}
              {generationMode === 'video' && (
                <List
                  size="small"
                  header="Storyboard preview"
                  bordered
                  dataSource={splitStoryboard(activeVariant?.content)}
                  renderItem={(item, index) => (
                    <List.Item>
                      <Space direction="vertical" size={0}>
                        <Typography.Text strong>Scene {index + 1}</Typography.Text>
                        <Typography.Text>{item}</Typography.Text>
                      </Space>
                    </List.Item>
                  )}
                />
              )}
            </>
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={`Generate a ${modeConfig.label.toLowerCase()} pack to compare variants here.`}
            />
          )}
        </Space>
      </Card>

      <Card title="Visual / Production Preview">
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={12}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Typography.Text strong>
                {generationMode === 'video' ? 'Video production notes' : generationMode === 'flyer' ? 'Flyer layout notes' : 'Campaign preview'}
              </Typography.Text>
              <Typography.Paragraph type="secondary">
                {generationMode === 'video'
                  ? 'Use this as a pre-production plan for a short-form video: hook, scenes, captions, voiceover, and CTA.'
                  : generationMode === 'flyer'
                    ? 'Use the generated copy with the visual asset request to produce a clean promotional flyer.'
                    : 'Use the selected copy as the source asset for campaigns, social posts, or automations.'}
              </Typography.Paragraph>
              <Space wrap>
                <Tag color="blue">{briefValues.channel || 'channel pending'}</Tag>
                <Tag color="purple">{briefValues.audience || 'audience pending'}</Tag>
                <Tag>{briefValues.cta || 'CTA pending'}</Tag>
              </Space>
            </Space>
          </Col>
          <Col xs={24} lg={12}>
            <div
              style={{
                minHeight: 180,
                border: '1px dashed #d9d9d9',
                borderRadius: 8,
                padding: 16,
                background: '#fafafa',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                textAlign: 'center',
              }}
            >
              {brandAsset?.mediaUrl ? (
                <img
                  src={brandAsset.mediaUrl}
                  alt="Generated brand asset"
                  style={{ maxWidth: '100%', maxHeight: 220, objectFit: 'contain', borderRadius: 8 }}
                />
              ) : (
                <Space direction="vertical">
                  {generationMode === 'video' ? <VideoCameraOutlined /> : <PictureOutlined />}
                  <Typography.Text>
                    {generationMode === 'video'
                      ? 'Generate a visual asset to create a keyframe or cover direction.'
                      : 'Generate a visual asset to preview flyer or campaign imagery.'}
                  </Typography.Text>
                </Space>
              )}
            </div>
          </Col>
        </Row>
      </Card>

      <Card title="Recent Reusable Assets">
        <Space direction="vertical" size={12} style={{ width: '100%' }}>
          <Space wrap>
            <Select
              allowClear
              placeholder="Filter by type"
              style={{ minWidth: 160 }}
              value={assetTypeFilter}
              onChange={setAssetTypeFilter}
              options={CONTENT_TYPE_OPTIONS}
            />
            <Select
              allowClear
              placeholder="Filter by provider"
              style={{ minWidth: 160 }}
              value={providerFilter}
              onChange={setProviderFilter}
              options={[
                { value: 'kimi', label: 'Kimi' },
                { value: 'fal', label: 'Fal' },
              ]}
            />
          </Space>
          <Table
            rowKey="_id"
            loading={loading}
            dataSource={filteredAssets}
            pagination={false}
            columns={[
              { title: 'Title', dataIndex: 'title' },
              { title: 'Type', dataIndex: 'type', render: (value) => <Tag>{value}</Tag> },
              { title: 'Provider', dataIndex: 'provider', render: (value) => value || '-' },
              {
                title: 'Use',
                render: (_, record) => (
                  <Button
                    size="small"
                    onClick={() => {
                      const importedMode = normalizeModeFromType(record.type);
                      form.setFieldsValue({
                        generationMode: importedMode,
                        type: record.type,
                        prompt: record.prompt,
                        brandName: record.brandContext?.brandName,
                        linkedCampaignId: record.brandContext?.campaignId,
                        linkedSegmentId: record.brandContext?.audienceSegment,
                      });
                      setVariants([{ key: record._id, label: 'Imported Asset', content: record.content, asset: record }]);
                      setSelectedVariant(0);
                      setCurrentStep(4);
                    }}
                  >
                    Import
                  </Button>
                ),
              },
            ]}
          />
        </Space>
      </Card>
    </Space>
  );

  const sidebar = (
    <>
      <Card title="Linked Context" size="small">
        <List
          size="small"
          dataSource={[
            ['Campaign', selectedCampaign?.name || 'Not linked'],
            ['Audience Segment', selectedSegment?.name || 'Not linked'],
            ['Audience Summary', buildAudienceSummary(selectedSegment)],
            ['Production Mode', modeConfig.label],
            ['Current Variant', activeVariant?.label || 'None'],
          ]}
          renderItem={([label, value]) => (
            <List.Item>
              <Space direction="vertical" size={0}>
                <strong>{label}</strong>
                <span>{value}</span>
              </Space>
            </List.Item>
          )}
        />
      </Card>

      <Card title="Brand Asset" size="small">
        <Space direction="vertical" style={{ width: '100%' }}>
          {brandAsset?.mediaUrl && (
            <img
              src={brandAsset.mediaUrl}
              alt="Generated brand asset"
              style={{ width: '100%', maxHeight: 180, objectFit: 'cover', borderRadius: 8 }}
            />
          )}
          <div style={{ whiteSpace: 'pre-wrap' }}>
            {brandAsset?.content || brandAsset?.message || brandAsset?.mediaUrl || 'Generate a visual asset to see the response here.'}
          </div>
        </Space>
      </Card>

      <Card title="Publish / Handoff" size="small">
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button type="primary" onClick={handoffToMarketing} disabled={!activeVariant?.content}>
            Use in Campaign
          </Button>
          <Button onClick={createSocialDraft} disabled={!activeVariant?.content}>
            Create Social Post Draft
          </Button>
          <Button onClick={handoffToAutomations} disabled={!activeVariant?.content}>
            Attach to Automation
          </Button>
          <Button onClick={createProductionTask} disabled={!activeVariant?.content && !brandAsset}>
            Create Production Task
          </Button>
          <Button icon={<ReloadOutlined />} onClick={load}>
            Refresh Assets
          </Button>
        </Space>
      </Card>

      <Card title="Next Actions" size="small">
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button>
            <Link to="/tasks">Open Task Board</Link>
          </Button>
          <Button>
            <Link to="/marketing">Open Marketing Workspace</Link>
          </Button>
          <Button>
            <Link to="/automations">Open Automations Workspace</Link>
          </Button>
        </Space>
      </Card>
    </>
  );

  return (
    <GrowthWorkspaceShell
      title="AI Studio"
      description="Create content, compare variants, pair it with brand assets, and hand it directly into growth workflows."
      permission="ai.studio.read"
      currentStep={currentStep}
      stepItems={STEP_ITEMS}
      statusTags={[
        { label: modeConfig.label, color: generationMode === 'video' ? 'orange' : generationMode === 'flyer' ? 'purple' : 'blue' },
        { label: variants.length ? 'Draft Ready' : 'Draft', color: variants.length ? 'green' : 'blue' },
        { label: brandAsset ? 'Brand Asset Ready' : 'Needs Asset', color: brandAsset ? 'purple' : 'default' },
      ]}
      linkedRecords={[
        { label: 'Campaign', value: selectedCampaign?.name },
        { label: 'Segment', value: selectedSegment?.name },
      ]}
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={load}>
            Refresh
          </Button>
          <Button disabled={!canGenerate} onClick={generateVariants}>
            Generate {modeConfig.label}
          </Button>
          <Button type="primary" disabled={!canGenerate} onClick={generateBrandAsset}>
            Visual Asset
          </Button>
        </Space>
      }
      main={main}
      sidebar={sidebar}
    />
  );
}
