import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useRecipe } from '../hooks/useRecipe';
import { useToastContext } from '../App';
import { RecipeForm, type RecipeFormData } from '../components/RecipeForm';
import { createRecipe, updateRecipe, deleteRecipe, fetchRecipeTags, assignTagToRecipe, removeTagFromRecipe } from '../services/api';
import type { Tag, Ingredient, Recipe } from '../types/recipe';
import { loadPhotoManifest } from '../assets/photoManifest';
import { UiButton, UiCard, UiChip, UiPage, UiSection } from '../components/ui/primitives';

interface PhotoManifest {
  assets?: {
    photos?: {
      detail?: {
        default16x9?: string;
      };
      list?: {
        default4x3?: string;
      };
      category?: Record<string, { localPath?: string | null; remoteCandidate?: string | null }>;
    };
  };
}

type IconName =
  | 'clock'
  | 'users'
  | 'chef-hat'
  | 'list'
  | 'book-open'
  | 'edit'
  | 'cook'
  | 'print'
  | 'share'
  | 'trash'
  | 'arrow-left'
  | 'link'
  | 'note'
  | 'tag';

function Icon({ name, className = 'h-4 w-4', size = 16 }: { name: IconName; className?: string; size?: number }) {
  const common = {
    className,
    viewBox: '0 0 24 24',
    width: size,
    height: size,
    style: {
      width: `${size}px`,
      height: `${size}px`,
      minWidth: `${size}px`,
      minHeight: `${size}px`,
      maxWidth: `${size}px`,
      maxHeight: `${size}px`,
      flexShrink: 0,
    },
    fill: 'none',
    stroke: 'currentColor',
    strokeWidth: 2,
    strokeLinecap: 'round' as const,
    strokeLinejoin: 'round' as const,
    'aria-hidden': true,
  };

  switch (name) {
    case 'clock':
      return <svg {...common}><circle cx="12" cy="12" r="9" /><path d="M12 7v6l4 2" /></svg>;
    case 'users':
      return <svg {...common}><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></svg>;
    case 'chef-hat':
      return <svg {...common}><path d="M6 18h12" /><path d="M6 22h12" /><path d="M7 18v-7a4 4 0 1 1 7-2 3 3 0 1 1 4 3v6" /></svg>;
    case 'list':
      return <svg {...common}><path d="M8 6h13" /><path d="M8 12h13" /><path d="M8 18h13" /><path d="M3 6h.01" /><path d="M3 12h.01" /><path d="M3 18h.01" /></svg>;
    case 'book-open':
      return <svg {...common}><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" /><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" /></svg>;
    case 'edit':
      return <svg {...common}><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" /></svg>;
    case 'cook':
      return <svg {...common}><path d="M4 12h16" /><path d="M6 12v6a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-6" /><path d="M8 12V8a4 4 0 1 1 8 0v4" /></svg>;
    case 'print':
      return <svg {...common}><path d="M6 9V2h12v7" /><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" /><path d="M6 14h12v8H6z" /></svg>;
    case 'share':
      return <svg {...common}><circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" /><path d="m8.6 13.5 6.8 4" /><path d="m15.4 6.5-6.8 4" /></svg>;
    case 'trash':
      return <svg {...common}><path d="M3 6h18" /><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" /><path d="M10 11v6" /><path d="M14 11v6" /></svg>;
    case 'arrow-left':
      return <svg {...common}><path d="m12 19-7-7 7-7" /><path d="M19 12H5" /></svg>;
    case 'link':
      return <svg {...common}><path d="M10 13a5 5 0 0 0 7.07 0l2.83-2.83a5 5 0 0 0-7.07-7.07L10 5" /><path d="M14 11a5 5 0 0 0-7.07 0L4.1 13.83a5 5 0 1 0 7.07 7.07L14 19" /></svg>;
    case 'note':
      return <svg {...common}><path d="M8 2h8l4 4v14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z" /><path d="M16 2v4h4" /><path d="M10 13h4" /><path d="M10 17h4" /><path d="M10 9h2" /></svg>;
    case 'tag':
      return <svg {...common}><path d="M20.59 13.41 11 3.83A2 2 0 0 0 9.59 3H4a1 1 0 0 0-1 1v5.59A2 2 0 0 0 3.83 11l9.58 9.59a2 2 0 0 0 2.83 0l4.35-4.35a2 2 0 0 0 0-2.83Z" /><circle cx="7.5" cy="7.5" r="1.1" /></svg>;
    default:
      return null;
  }
}

function normalizeImageUrl(value: unknown): string | null {
  if (typeof value !== 'string') return null;
  const trimmed = value.trim();
  if (!trimmed) return null;
  if (trimmed.startsWith('/') || trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
    return trimmed;
  }
  return null;
}

function extractRecipeImageUrl(recipe: Recipe | null): string | null {
  if (!recipe) return null;
  const dynamicRecipe = recipe as unknown as Record<string, unknown>;
  const candidateKeys = [
    'image_url',
    'imageUrl',
    'photo_url',
    'photoUrl',
    'hero_image_url',
    'heroImageUrl',
    'thumbnail_url',
    'thumbnailUrl',
  ];

  for (const key of candidateKeys) {
    const normalized = normalizeImageUrl(dynamicRecipe[key]);
    if (normalized) return normalized;
  }

  return null;
}

function inferCategoryKey(recipe: Recipe | null, tags: Tag[]): string | null {
  const title = recipe?.title ?? '';
  const haystack = `${title} ${tags.map((tag) => tag.name).join(' ')}`.toLowerCase();

  if (haystack.includes('breakfast') || haystack.includes('egg') || haystack.includes('toast')) return 'breakfast';
  if (haystack.includes('dessert') || haystack.includes('cake') || haystack.includes('cookie') || haystack.includes('sweet')) return 'dessert';
  if (haystack.includes('dinner') || haystack.includes('steak') || haystack.includes('pasta') || haystack.includes('roast')) return 'dinner';

  return null;
}

function buildDetailImageCandidates(recipe: Recipe | null, tags: Tag[], manifest: PhotoManifest | null): string[] {
  const candidates: Array<string | null | undefined> = [];
  const recipeImage = extractRecipeImageUrl(recipe);
  candidates.push(recipeImage);

  const categoryKey = inferCategoryKey(recipe, tags);
  if (categoryKey && manifest?.assets?.photos?.category?.[categoryKey]) {
    const categoryAsset = manifest.assets.photos.category[categoryKey];
    candidates.push(categoryAsset.localPath ?? categoryAsset.remoteCandidate ?? null);
  }

  candidates.push(manifest?.assets?.photos?.detail?.default16x9);
  candidates.push(manifest?.assets?.photos?.list?.default4x3);
  candidates.push('/assets/food/placeholder-recipe.svg');

  const seen = new Set<string>();
  return candidates
    .map((item) => normalizeImageUrl(item))
    .filter((item): item is string => {
      if (!item || seen.has(item)) return false;
      seen.add(item);
      return true;
    });
}

/**
 * RecipeDetailPage - View, create, and edit recipes (T06 detail visual upgrade)
 */
export function RecipeDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const toast = useToastContext();
  const recipeId = id === 'new' ? null : (id ? parseInt(id, 10) : null);
  const { recipe, loading, error } = useRecipe(recipeId);
  const [isEditing, setIsEditing] = useState(recipeId === null);
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [recipeTags, setRecipeTags] = useState<Tag[]>([]);
  const [isDeleting, setIsDeleting] = useState(false);
  const [photoManifest, setPhotoManifest] = useState<PhotoManifest | null>(null);
  const [detailImageCandidates, setDetailImageCandidates] = useState<string[]>(['/assets/food/placeholder-recipe.svg']);
  const [detailImageIndex, setDetailImageIndex] = useState(0);

  useEffect(() => {
    setDetailImageIndex(0);
  }, [recipeId]);

  useEffect(() => {
    loadPhotoManifest<PhotoManifest>()
      .then((manifest) => setPhotoManifest(manifest))
      .catch(() => {
        setPhotoManifest(null);
      });
  }, []);

  useEffect(() => {
    const candidates = buildDetailImageCandidates(recipe, recipeTags, photoManifest);
    setDetailImageCandidates(candidates.length > 0 ? candidates : ['/assets/food/placeholder-recipe.svg']);
    setDetailImageIndex(0);
  }, [recipe, recipeTags, photoManifest]);

  useEffect(() => {
    if (recipeId !== null) {
      fetchRecipeTags(recipeId)
        .then(setRecipeTags)
        .catch((err) => {
          console.error('Failed to load recipe tags:', err);
          toast.error('Failed to load recipe tags');
        });
    }
  }, [recipeId, toast]);

  function toApiIngredients(ingredients: string[]): Ingredient[] {
    return ingredients.map((item, idx) => ({
      id: 0,
      recipe_id: 0,
      position: idx + 1,
      item,
      quantity: null,
      unit: null,
      notes: null,
    }));
  }

  const handleSubmit = async (data: RecipeFormData, tags: Tag[]) => {
    try {
      if (recipeId === null) {
        const newRecipe = await createRecipe({
          ...data,
          ingredients: toApiIngredients(data.ingredients),
          instructions: data.instructions,
        });
        for (const tag of tags) {
          try {
            await assignTagToRecipe(newRecipe.id, tag.id);
          } catch {
            // no-op
          }
        }
        toast.success('Recipe created successfully!');
        navigate(`/recipe/${newRecipe.id}`);
      } else {
        await updateRecipe(recipeId, {
          ...data,
          ingredients: toApiIngredients(data.ingredients),
          instructions: data.instructions,
        });
        const currentTagIds = recipeTags.map((t) => t.id);
        const newTagIds = tags.map((t) => t.id);
        for (const tagId of currentTagIds) {
          if (!newTagIds.includes(tagId)) {
            try {
              await removeTagFromRecipe(recipeId, tagId);
            } catch {
              // no-op
            }
          }
        }
        for (const tagId of newTagIds) {
          if (!currentTagIds.includes(tagId)) {
            try {
              await assignTagToRecipe(recipeId, tagId);
            } catch {
              // no-op
            }
          }
        }
        toast.success('Recipe updated successfully!');
        setIsEditing(false);
        window.location.reload();
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to save recipe';
      toast.error(errorMessage);
      throw err;
    }
  };

  const handleDelete = async () => {
    if (recipeId === null) return;
    try {
      setIsDeleting(true);
      await deleteRecipe(recipeId);
      toast.success('Recipe deleted successfully');
      navigate('/');
    } catch (err) {
      setIsDeleting(false);
      setDeleteConfirm(false);
      const errorMessage = err instanceof Error ? err.message : 'Failed to delete recipe';
      toast.error(errorMessage);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  const handleShare = async () => {
    const title = recipe?.title ?? 'Recipe';
    const shareText = recipe?.description ?? 'Check out this recipe';
    const shareUrl = window.location.href;

    try {
      if (navigator.share) {
        await navigator.share({
          title,
          text: shareText,
          url: shareUrl,
        });
        return;
      }
      await navigator.clipboard.writeText(shareUrl);
      toast.success('Recipe link copied to clipboard');
    } catch {
      toast.error('Could not share recipe right now');
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <div className="inline-block h-9 w-9 animate-spin rounded-full border-b-2 border-primary"></div>
        <p className="mt-6 text-base font-medium text-[var(--text-dim)]">Loading recipe...</p>
      </div>
    );
  }

  if (error) {
    return (
      <UiSection className="mx-auto mt-12 flex max-w-xl flex-col items-center border border-[color:var(--color-error-light)] bg-[color:var(--color-error-light)]/45 p-8 text-center" padding="none">
        <h3 className="mb-3 text-xl font-bold text-[color:var(--color-error)]">Error Loading Recipe</h3>
        <p className="mb-2 text-base text-[var(--text-dim)]">{error}</p>
        <Link to="/" className="ui-btn ui-btn-primary mt-4">← Back to recipes</Link>
      </UiSection>
    );
  }

  if (recipeId === null) {
    return (
      <div className="mx-auto max-w-3xl pt-8">
        <UiSection className="mb-6 overflow-hidden border border-[var(--border)] bg-gradient-to-br from-white via-[var(--surface-muted)]/70 to-[var(--bg-alt)]/70 shadow-card" padding="none">
          <div className="flex items-center justify-between px-6 py-5">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-[var(--color-primary)]">New Recipe</p>
              <h2 className="text-3xl font-bold text-[var(--text-h)]">Create New Recipe</h2>
              <p className="mt-1 text-base text-[var(--text-dim)]">Fill in the details below to add a new recipe.</p>
            </div>
            <UiChip tone="subtle" className="hidden border-[var(--border)] bg-white/80 px-4 py-2 text-sm font-semibold text-[var(--color-primary)] md:inline-flex">Draft</UiChip>
          </div>
        </UiSection>
        <UiCard className="p-8">
          <RecipeForm initialTags={[]} onSubmit={handleSubmit} onCancel={() => navigate('/')} submitLabel="Create Recipe" />
        </UiCard>
      </div>
    );
  }

  if (!recipe) {
    return (
      <UiSection className="mx-auto mt-12 flex max-w-md flex-col items-center border border-[color:var(--color-warning-light)] bg-[color:var(--color-warning-light)]/45 p-8 text-center" padding="none">
        <h3 className="mb-2 text-xl font-bold text-[color:var(--color-warning)]">Recipe Not Found</h3>
        <p className="mb-2 text-base text-[var(--text-dim)]">The recipe you are looking for does not exist.</p>
        <Link to="/" className="ui-btn ui-btn-primary mt-4">← Back to recipes</Link>
      </UiSection>
    );
  }

  if (isEditing) {
    return (
      <div className="mx-auto max-w-3xl pt-8">
        <UiSection className="mb-6 overflow-hidden border border-[var(--border)] bg-gradient-to-br from-white via-[var(--surface-muted)]/70 to-[var(--bg-alt)]/70 shadow-card" padding="none">
          <div className="flex items-center justify-between px-6 py-5">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-[var(--color-primary)]">Editing</p>
              <h2 className="text-3xl font-bold text-[var(--text-h)]">Edit Recipe</h2>
              <p className="mt-1 text-base text-[var(--text-dim)]">Update recipe information below.</p>
            </div>
            <UiChip tone="subtle" className="hidden border-[var(--border)] bg-white/80 px-4 py-2 text-sm font-semibold text-[var(--color-primary)] md:inline-flex">Edit</UiChip>
          </div>
        </UiSection>
        <UiCard className="p-8">
          <RecipeForm recipe={recipe} initialTags={recipeTags} onSubmit={handleSubmit} onCancel={() => setIsEditing(false)} submitLabel="Save Changes" />
        </UiCard>
      </div>
    );
  }

  const heroSrc = detailImageCandidates[Math.min(detailImageIndex, detailImageCandidates.length - 1)] ?? '/assets/food/placeholder-recipe.svg';

  const ingredients = Array.isArray(recipe.ingredients)
    ? recipe.ingredients
        .map((ingredient) => ('item' in ingredient ? ingredient.item : String(ingredient)))
        .filter(Boolean)
    : [];

  const instructions = Array.isArray(recipe.instructions)
    ? recipe.instructions.filter(Boolean)
    : Array.isArray(recipe.steps)
      ? recipe.steps
          .map((step) => step?.instruction)
          .filter((instruction): instruction is string => Boolean(instruction))
      : [];

  const totalTime = (recipe.prep_time_minutes || 0) + (recipe.cook_time_minutes || 0);
  const mobileActionButtonClass = 'ui-btn ui-btn-secondary min-h-[2.25rem] w-full min-w-0 justify-start gap-1.5 px-2.5 py-2 text-xs leading-4 sm:text-sm';
  const mobilePrimaryActionButtonClass = 'ui-btn ui-btn-primary min-h-[2.25rem] w-full min-w-0 justify-start gap-1.5 px-2.5 py-2 text-xs leading-4 sm:text-sm';
  const desktopActionButtonClass = 'ui-btn ui-btn-secondary w-full min-h-[2.5rem] min-w-0 justify-start gap-2 px-3 py-2 text-sm leading-4';
  const metadataBadges = [
    recipe.servings ? { label: `${recipe.servings} servings`, icon: 'users' as const } : null,
    recipe.prep_time_minutes ? { label: `${recipe.prep_time_minutes} min prep`, icon: 'clock' as const } : null,
    recipe.cook_time_minutes ? { label: `${recipe.cook_time_minutes} min cook`, icon: 'chef-hat' as const } : null,
    totalTime > 0 ? { label: `${totalTime} min total`, icon: 'clock' as const } : null,
    ingredients.length > 0 ? { label: `${ingredients.length} ingredients`, icon: 'list' as const } : null,
  ].filter(Boolean) as Array<{ label: string; icon: IconName }>;

  return (
    <UiPage className="max-w-5xl px-4 pt-5 pb-20 sm:px-5 md:px-6 lg:px-8 md:pt-6 md:pb-8">
      <section className="ui-section relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-[var(--color-primary-light)]/70 via-[var(--surface-muted)]/60 to-[var(--bg-alt)]/65" aria-hidden="true" />
        <div className="relative grid grid-cols-1 gap-6 px-5 py-5 sm:px-6 sm:py-6 md:grid-cols-[1.2fr_1fr] md:items-stretch md:gap-8 md:px-8 md:py-7">
          <div className="min-w-0 space-y-5 px-0.5 sm:px-1 md:space-y-6 md:px-0">
            <p className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--color-primary-dark)]">Recipe Detail</p>
            <h1 className="max-w-[24ch] break-words text-xl font-black leading-tight text-[var(--text-h)] sm:text-2xl md:text-3xl">{recipe.title}</h1>
            {recipe.description && (
              <p className="max-w-prose break-words text-sm leading-relaxed text-[var(--text-dim)] sm:text-base">{recipe.description}</p>
            )}

            {metadataBadges.length > 0 && (
              <div className="-mx-0.5 flex flex-wrap gap-2.5 px-0.5 pt-1 sm:mx-0 sm:px-0">
                {metadataBadges.map((badge) => (
                  <UiChip key={badge.label} className="gap-1.5 border-[var(--border)] bg-white/90 px-3.5 py-1.5 text-xs font-semibold text-[var(--text)] shadow-sm">
                    <Icon name={badge.icon} className="h-3 w-3 text-[var(--text-dim)]" />
                    {badge.label}
                  </UiChip>
                ))}
              </div>
            )}

            {recipeTags.length > 0 && (
              <div className="-mx-0.5 flex flex-wrap gap-2.5 px-0.5 pt-1 sm:mx-0 sm:px-0">
                {recipeTags.map((tag) => (
                  <span
                    key={tag.id}
                    className="inline-flex max-w-full items-center gap-2 rounded-full border border-white/70 px-4 py-2 text-xs font-semibold leading-4 text-[var(--text-h)] shadow-sm sm:px-5"
                    style={{ backgroundColor: `${tag.color || '#E2E8F0'}cc` }}
                  >
                    <Icon name="tag" className="h-3 w-3 shrink-0 text-[var(--text-dim)]" />
                    <span className="truncate">{tag.name}</span>
                  </span>
                ))}
              </div>
            )}
          </div>

          <div className="relative overflow-hidden rounded-2xl border border-white/70 bg-white/60 shadow-card">
            <img
              src={heroSrc}
              alt={recipe.title}
              className="h-full min-h-[240px] w-full object-cover"
              onError={() => {
                if (detailImageIndex < detailImageCandidates.length - 1) {
                  setDetailImageIndex((idx) => idx + 1);
                }
              }}
            />
            <div className="absolute bottom-3 left-3 inline-flex max-w-[calc(100%-1.5rem)] items-center gap-1.5 rounded-full border border-white/80 bg-black/55 px-3 py-1 text-xs font-semibold text-white backdrop-blur">
              <Icon name="book-open" className="h-3 w-3" />
              {instructions.length > 0 ? `${instructions.length} steps` : 'Recipe overview'}
            </div>
          </div>
        </div>
      </section>

      <section className="mt-5 md:hidden min-w-0">
        <div className="sticky bottom-3 z-20 rounded-2xl border border-[var(--border)] bg-white/95 p-2.5 shadow-[0_10px_30px_rgba(15,23,42,0.15)] backdrop-blur">
          <div className="grid grid-cols-2 gap-2 min-w-0 text-xs">
            <button onClick={() => setIsEditing(true)} className={mobileActionButtonClass}><Icon name="edit" className="h-3.5 w-3.5" size={14} /><span className="truncate">Edit</span></button>
            <Link to={`/recipe/${recipe.id}/cook`} className={mobilePrimaryActionButtonClass}><Icon name="cook" className="h-3.5 w-3.5" size={14} /><span className="truncate">Cook</span></Link>
            <button onClick={handlePrint} className={mobileActionButtonClass}><Icon name="print" className="h-3.5 w-3.5" size={14} /><span className="truncate">Print</span></button>
            <button onClick={handleShare} className={mobileActionButtonClass}><Icon name="share" className="h-3.5 w-3.5" size={14} /><span className="truncate">Share</span></button>
            {!deleteConfirm ? (
              <UiButton onClick={() => setDeleteConfirm(true)} className="col-span-2 min-h-[2.25rem] w-full min-w-0 justify-center gap-1.5 border border-[color:var(--color-error-light)] bg-[color:var(--color-error-light)] px-2.5 py-2 text-xs leading-4 text-[color:var(--color-error)] sm:text-sm"><Icon name="trash" className="h-3.5 w-3.5" size={14} /><span className="truncate">Delete</span></UiButton>
            ) : (
              <div className="col-span-2 grid grid-cols-1 gap-2">
                <UiButton onClick={handleDelete} disabled={isDeleting} className="min-h-[2.25rem] w-full min-w-0 border border-[color:var(--color-error)] bg-[color:var(--color-error)] px-2.5 py-2 text-xs leading-4 text-white disabled:opacity-60 sm:text-sm">{isDeleting ? 'Deleting...' : 'Confirm delete'}</UiButton>
                <UiButton onClick={() => setDeleteConfirm(false)} disabled={isDeleting} className="min-h-[2.25rem] w-full min-w-0 px-2.5 py-2 text-xs leading-4 sm:text-sm">Cancel</UiButton>
              </div>
            )}
          </div>
        </div>
      </section>

      <div className="mt-7 grid grid-cols-1 gap-7 min-w-0 lg:grid-cols-[minmax(0,1fr)_300px]">
        <div className="space-y-7 min-w-0">
          <section className="ui-card overflow-hidden">
            <div className="border-b border-[var(--border)] bg-gradient-to-r from-[var(--surface-muted)] to-white px-6 py-4 sm:px-7 md:px-8">
              <h2 className="inline-flex items-center gap-2 text-lg sm:text-xl font-bold text-[var(--text-h)]"><Icon name="list" className="h-3.5 w-3.5 text-[var(--color-primary)]" />Ingredients</h2>
              <p className="mt-1 text-sm leading-relaxed text-[var(--text-dim)]">Gather these first so cooking goes smoothly.</p>
            </div>
            <ul className="m-3 space-y-4 rounded-2xl border border-[var(--border)] bg-white/80 px-4 py-5 sm:m-4 sm:px-6 md:px-7 md:py-6">
              {ingredients.length > 0 ? (
                ingredients.map((ingredient, index) => (
                  <li
                    key={`${ingredient}-${index}`}
                    className="grid min-w-0 grid-cols-[1.85rem_minmax(0,1fr)] items-start gap-x-3.5 rounded-xl border border-[var(--border)] bg-[var(--surface-muted)]/60 px-4 py-3.5 sm:px-5"
                  >
                    <span className="mt-0.5 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[var(--border)] bg-[var(--color-primary-light)] text-xs font-semibold text-[var(--color-primary-dark)]">
                      {index + 1}
                    </span>
                    <span className="min-w-0 break-words pt-0.5 text-sm leading-6 text-[var(--text)]">{ingredient}</span>
                  </li>
                ))
              ) : (
                <li className="rounded-xl border border-dashed border-[var(--border)] bg-white px-4 py-6 text-sm text-[var(--text-dim)] sm:px-5">
                  No ingredients listed yet.
                </li>
              )}
            </ul>
          </section>

          <section className="ui-card overflow-hidden">
            <div className="border-b border-[var(--border)] bg-gradient-to-r from-[var(--surface-muted)] to-white px-6 py-4 sm:px-7 md:px-8">
              <h2 className="inline-flex items-center gap-2 text-lg sm:text-xl font-bold text-[var(--text-h)]"><Icon name="book-open" className="h-3.5 w-3.5 text-[var(--color-primary)]" />Instructions</h2>
              <p className="mt-1 text-sm leading-relaxed text-[var(--text-dim)]">Step-by-step flow for better cooking rhythm.</p>
            </div>
            <ol className="m-3 space-y-4 rounded-2xl border border-[var(--border)] bg-white/80 px-4 py-5 sm:m-4 sm:px-6 md:px-7 md:py-6">
              {instructions.length > 0 ? (
                instructions.map((instruction, index) => (
                  <li key={`${instruction}-${index}`} className="grid min-w-0 grid-cols-[2rem_minmax(0,1fr)] items-start gap-x-3.5 rounded-xl border border-[var(--border)] bg-white px-4 py-4 sm:px-5">
                    <span className="mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-primary)] text-sm font-semibold text-white">
                      {index + 1}
                    </span>
                    <span className="min-w-0 break-words pt-1 text-sm leading-6 text-[var(--text)]">{instruction}</span>
                  </li>
                ))
              ) : (
                <li className="rounded-xl border border-dashed border-[var(--border)] bg-white px-4 py-6 text-sm text-[var(--text-dim)] sm:px-5">
                  No instructions listed yet.
                </li>
              )}
            </ol>
          </section>

          {(recipe.source_url || recipe.notes) && (
            <section className="ui-card overflow-hidden">
              <div className="border-b border-[var(--border)] bg-gradient-to-r from-[var(--surface-muted)] to-white px-6 py-4 sm:px-7 md:px-8">
                <h3 className="text-lg sm:text-xl font-semibold text-[var(--text-h)]">Additional Information</h3>
              </div>
              <div className="m-3 space-y-5 rounded-2xl border border-[var(--border)] bg-white/80 px-4 py-5 sm:m-4 sm:px-6 md:px-7 md:py-6">
                {recipe.source_url && (
                  <div className="space-y-2 rounded-xl border border-[var(--border)] bg-[var(--surface-muted)]/40 px-4 py-3.5 sm:px-5">
                    <div className="inline-flex items-center gap-1.5 text-sm font-medium text-[var(--text-dim)]"><Icon name="link" className="h-3 w-3" />Source</div>
                    <a href={recipe.source_url} target="_blank" rel="noopener noreferrer" className="break-words text-[var(--color-primary)] underline decoration-[1.5px] underline-offset-2 hover:text-[var(--color-primary-dark)]">
                      {recipe.source_url}
                    </a>
                  </div>
                )}
                {recipe.notes && (
                  <div className="space-y-2 rounded-xl border border-[var(--border)] bg-[var(--surface-muted)]/40 px-4 py-3.5 sm:px-5">
                    <div className="inline-flex items-center gap-1.5 text-sm font-medium text-[var(--text-dim)]"><Icon name="note" className="h-3 w-3" />Notes</div>
                    <p className="max-w-prose whitespace-pre-wrap break-words text-sm leading-relaxed text-[var(--text)] sm:text-base">{recipe.notes}</p>
                  </div>
                )}
              </div>
            </section>
          )}
        </div>

        <aside className="hidden lg:block">
          <div className="sticky top-6 space-y-3 rounded-2xl border border-[var(--border)] bg-white/95 p-4 shadow-card">
            <p className="text-xs font-semibold uppercase tracking-[0.15em] text-[var(--text-dim)]">Quick Actions</p>
            <button onClick={() => setIsEditing(true)} className={desktopActionButtonClass}><Icon name="edit" className="h-3.5 w-3.5" size={15} /><span className="truncate">Edit recipe</span></button>
            <Link to={`/recipe/${recipe.id}/cook`} className="ui-btn ui-btn-primary w-full min-h-[2.5rem] min-w-0 justify-start gap-2 px-3 py-2 text-sm leading-4"><Icon name="cook" className="h-3.5 w-3.5" size={15} /><span className="truncate">Open cook mode</span></Link>
            <button onClick={handlePrint} className={desktopActionButtonClass}><Icon name="print" className="h-3.5 w-3.5" size={15} /><span className="truncate">Print recipe</span></button>
            <button onClick={handleShare} className={desktopActionButtonClass}><Icon name="share" className="h-3.5 w-3.5" size={15} /><span className="truncate">Share recipe</span></button>
            {!deleteConfirm ? (
              <UiButton onClick={() => setDeleteConfirm(true)} className="w-full min-h-[2.5rem] min-w-0 justify-start gap-2 border border-[color:var(--color-error-light)] bg-[color:var(--color-error-light)] px-3 py-2 text-sm leading-4 text-[color:var(--color-error)]"><Icon name="trash" className="h-3.5 w-3.5" size={15} /><span className="truncate">Delete recipe</span></UiButton>
            ) : (
              <div className="grid grid-cols-2 gap-2">
                <UiButton onClick={handleDelete} disabled={isDeleting} className="min-h-[2.5rem] min-w-0 border border-[color:var(--color-error)] bg-[color:var(--color-error)] px-3 py-2 text-sm leading-4 text-white disabled:opacity-60">
                  {isDeleting ? 'Deleting...' : 'Confirm'}
                </UiButton>
                <UiButton onClick={() => setDeleteConfirm(false)} disabled={isDeleting} className="min-h-[2.5rem] min-w-0 px-3 py-2 text-sm leading-4">
                  Cancel
                </UiButton>
              </div>
            )}
            <Link to="/" className={desktopActionButtonClass}><Icon name="arrow-left" className="h-3.5 w-3.5" size={15} /><span className="truncate">Back to all recipes</span></Link>
          </div>
        </aside>
      </div>

      <div className="mt-8 text-center lg:hidden">
        <Link to="/" className="inline-flex items-center gap-1.5 text-sm font-medium text-[var(--color-primary)] transition-colors hover:text-[var(--color-primary-dark)]"><Icon name="arrow-left" className="h-3 w-3" />Back to all recipes</Link>
      </div>
    </UiPage>
  );
}
