// Imagens de demonstração — otimizadas em WebP
const STOCK = {
  livingRoomDim:   'foto-original.webp',
  livingRoomBright:'manha-de-sol.webp',
  bedroomDim:      'foto-original.webp',
  bedroomBright:   'manha-de-sol.webp',
  kitchen:         'foto-original.webp',
  kitchenBright:   'hdr.webp',
  exterior:        'foto-original.webp',
  exteriorSunny:   'entardecer.webp',
  pool:            'hdr.webp',
  bathroom:        'manha-de-sol.webp',
  balcony:         'entardecer.webp',
  diningDark:      'foto-original.webp',
  diningNight:     'noite-acolhedora.webp',
  studio:          'hdr.webp',
  garden:          'entardecer.webp',
  neblina:         'neblina-montanha.webp',
  ultra:           'ultra-realismo.webp',
};

const PRESETS = [
  { id: 'luz-natural', name: 'Manhã de sol', emoji: null, tag: 'Mais popular',
    desc: 'Ideal se a foto foi tirada num dia nublado ou em um ambiente escuro. Traz a luz de uma manhã de sol fresca e natural.',
    demo: { before: STOCK.livingRoomDim, after: STOCK.livingRoomBright },
    accent: '#E8C98A',
    askCleanup: true,
    prompt: `Professional real estate photo retouching. Apply natural enhancements only — do not add, remove, or alter any objects, furniture, architecture, or structural elements in the scene.
Lighting & Atmosphere:
Transform the lighting to match a clear sunny morning at approximately 9:30 AM — bright, clean, fresh daylight with a slight cool-warm balance. Replace the overcast, rainy, flat lighting with natural morning sunlight entering through windows and openings, casting crisp but soft directional shadows. The light should feel open and airy, not heavy or dramatic. Sky visible through windows should appear as a clean bright blue morning sky. Maintain realistic light falloff and shadow behavior.
Wet Surfaces:
If the ground, pavement, deck, driveway, or any outdoor surface appears wet from rain, make it appear naturally dry while preserving the original texture and material underneath.
Color & White Balance:
Correct white balance to a clean neutral-warm tone (approx. 5000-5400K). Remove any color casts from artificial lighting or overcast conditions. Ensure whites are clean and bright, wood tones are natural, and greens in any vegetation look fresh and vibrant but realistic.
Technical Corrections:
Remove motion blur / camera shake artifacts, restore sharpness
Correct chromatic aberration on edges and high-contrast areas
Apply natural sharpening to architectural details, textures, and surfaces
Apply subtle HDR tone mapping: recover shadow detail and highlight detail while maintaining a natural, non-processed look
No halos, no over-saturated colors, no fake HDR look
Privacy:
If any license plates are visible on cars, apply a realistic blur to make them unreadable
If any people are present in the scene, remove them cleanly with seamless background reconstruction
Style reference: International standard Airbnb / luxury real estate listing photography. Clean, bright, inviting, fresh, editorial quality. The final image should look like it was professionally shot on a sunny morning with a full-frame camera and wide-angle lens — not AI-edited.` },
  { id: 'ceu-azul', name: 'Entardecer', tag: 'Blue hour',
    desc: 'Use quando a foto original estiver com uma luz dura da tarde ou sem graça. Cria o clima cinematográfico e dramático do anoitecer.',
    demo: { before: STOCK.exterior, after: STOCK.exteriorSunny },
    accent: '#8CA5B8',
    askCleanup: true,
    askIndoorLights: true,
    prompt: `Professional architectural photography retouching — editorial magazine quality. Apply enhancements only; do not add, remove, or alter any objects, furniture, architecture, or structural elements in the scene. Preserve all geometry, lines, and proportions exactly as in the original (overlay only — no geometric changes).
Lighting & Atmosphere: Transform the scene into a cinematic late-afternoon golden hour / early dusk, approximately 5:30–6:00 PM. Warm directional sunlight raking in low from the horizon, with a dramatic but natural sky transitioning from deep warm amber and soft coral near the horizon to muted blue-violet above. The mood should feel calm, moody, and refined — darker than midday but still with rich readable detail in shadows. Light should feel atmospheric and architectural, not flat. Subtle warm highlights catching edges of wood, concrete, glass, and metal. Windows and glass surfaces should reflect the warm sky naturally.
Wet Surfaces: If any surface appears wet from rain, restore it to a naturally dry state while preserving the original texture and material underneath.
Color & Tonality: Neutral, natural, editorial palette — no heavy saturation, no orange push, no teal-and-orange cliché. Clean warm-neutral white balance (approx. 4600–5000K) with preserved cool tones in the sky and shadows. Wood tones natural and honest, concrete neutral grey, vegetation muted and realistic. Deep but open shadows (no crushed blacks), controlled highlights in the sky, smooth tonal transitions. Slight filmic contrast curve.
Technical & Texture: Full-frame professional camera look (medium-format/Phase One / Hasselblad / full-frame mirrorless aesthetic) with wide-angle architectural lens. Sharp, clean micro-detail in textures — wood grain, concrete pores, fabric weave, glass. Remove motion blur, camera shake, and any phone-camera artifacts (over-sharpening, digital noise, HDR halos, aggressive local contrast). Correct chromatic aberration on high-contrast edges. Apply clean, natural HDR — full dynamic range recovery with zero "HDR look": no halos, no flat midtones, no oversaturated edges. Subtle, organic grain consistent with a high-end digital capture.
Privacy: Blur any visible license plates realistically. Remove any people cleanly with seamless background reconstruction.
Style reference: Editorial architectural photography — Architectural Digest, Dezeen, Wallpaper*, Openhouse magazine. The final image should look like a professional architecture photo shoot captured at late afternoon with a full-frame camera and tilt-shift / wide-angle lens — quiet, moody, refined, and unmistakably editorial. Not AI-edited, not phone, not real estate listing. Architecture portrait, not property ad.`,
    indoorLightsPrompt: `Interior Lighting:
Keep all interior lights turned ON and clearly visible through windows, doorways, and openings. Lamps, pendants, sconces, and any warm indoor light sources should emit a soft warm glow (approx. 2700-3000K) that complements the late afternoon exterior light. The interior should feel warm, inviting, and lived-in, with indoor light spilling naturally onto nearby surfaces (walls, floors, window frames) with realistic falloff. Maintain balanced exposure between the warm interior artificial lights and the moody late-afternoon exterior.` },
  { id: 'hdr', name: 'HDR editorial',
    desc: 'Salve fotos com janelas muito estouradas contra o sol. Simula um ensaio arquitetônico perfeitamente balanceado em bracket HDR.',
    demo: { before: STOCK.kitchen, after: STOCK.kitchenBright },
    accent: '#C96442',
    askCleanup: true,
    prompt: `Professional editorial architecture photography retouching. Apply natural enhancements only — do not add, remove, or alter any objects, furniture, architecture, or structural elements in the scene.

**Lighting & Atmosphere:** Transform the lighting to match a clear afternoon at approximately 4:00 PM — warm but restrained directional light typical of late-afternoon architectural shoots. Replace any overcast, rainy, or flat lighting with natural afternoon sunlight entering through windows and openings, casting longer, soft directional shadows with gentle contrast. The atmosphere should feel calm, composed, and editorial — not bright morning energy, not golden hour drama. Sky visible through windows should appear as a clean, even late-afternoon blue with subtle warmth near the horizon. Maintain realistic light falloff and shadow behavior.

**Wet Surfaces:** If the ground, pavement, deck, driveway, or any outdoor surface appears wet from rain, make it appear naturally dry while preserving the original texture and material underneath.

**Color & White Balance:** Neutral and natural palette — no stylized warmth, no cool tech look. Target approximately 5200-5500K with balanced, editorial color. Remove any color casts from artificial lighting. Whites should read clean and true, wood tones authentic, greens natural and matte rather than saturated. Avoid any digital "vibrancy" — think architectural magazine, not real estate listing.

**Camera & Texture:** The final image must read as captured on a professional full-frame camera with a high-quality wide-angle prime lens — NOT smartphone aesthetic. Preserve and emphasize natural sensor texture: subtle fine grain, organic micro-contrast, natural lens rendering, realistic depth and dimensionality. Avoid the over-smoothed, over-sharpened, over-processed look typical of phone HDR. No plastic skin-like surfaces, no digital smoothness on walls or materials.

**Technical Corrections:**
- Remove motion blur / camera shake, restore sharpness naturally
- Correct chromatic aberration on edges and high-contrast areas
- Apply refined sharpening only on architectural details and textures — never aggressive
- Clean HDR tone mapping: balanced highlights and shadows with full tonal range, but zero "HDR look" — no halos, no crushed blacks, no lifted shadows that flatten the image
- Preserve natural contrast curve of a professional raw file

**Privacy:** Blur any visible license plates realistically. Remove any people cleanly with seamless background reconstruction.

**Style reference:** Editorial architecture photography — Dezeen, ArchDaily, Wallpaper\\* magazine, Iwan Baan / Hélène Binet aesthetic. Composed, quiet, neutral, materially honest. The final image should look like a professional architectural essay shot on a full-frame camera at 4 PM, not AI-edited and not a real estate listing.` },
  { id: 'noite-acolhedora', name: 'Noite aconchegante', tag: 'Ambiente',
    desc: 'Ideal para fotos escuras ou tiradas sem tripé à noite. Corrige a geometria e entrega qualidade cristalina de longa exposição.',
    demo: { before: STOCK.diningDark, after: STOCK.diningNight },
    accent: '#8B5A3C',
    askCleanup: true,
    prompt: `Enhance this image to true professional long-exposure night photography quality, as captured by a high-end full-frame camera (Sony A7S III, Canon R5, Nikon Z8) mounted on a precision-leveled tripod with remote shutter release.
Framing and geometric correction (PRIORITY): This is the most critical adjustment. Straighten the horizon line with absolute precision. Correct any tilt, rotation, barrel distortion, or perspective keystoning. Ensure all vertical architectural lines are perfectly vertical and all horizontal lines are perfectly horizontal. Rebalance the composition applying the rule of thirds — reposition the visual weight so the main subject sits on a strong intersection point. Eliminate any feeling of a crooked, rushed, or handheld shot. The final framing must feel deliberate, architecturally precise, and composed through a leveled tripod head with electronic grid overlay. If the image feels tilted by even half a degree, it is incorrect.
Long-exposure night characteristics: Render smooth silky motion blur on moving elements (water as flowing glass, clouds with gentle directional streaking, any light sources in motion as natural trails). Static elements must remain tack-sharp. Simulate 10–30 second exposure. Night sky should show subtle natural ambient glow without star trailing unless contextually appropriate.
Optical behavior: Full-frame prime lens rendering (24mm–35mm), natural vignetting, smooth bokeh on out-of-focus light sources (circular or cat-eye shaped, never hexagonal or harsh). Clean resolution, no halos, no chromatic aberration, no digital sharpening artifacts.
Identity and scene preservation: Strictly preserve the subject's identity, anatomy, proportions, expression, and pose. Preserve the exact environment and spatial relationships. No background changes, no added or removed elements.
Night lighting: Maintain original lighting sources, direction, color temperature, and mood. Enhance with natural nighttime quality — warm practical lights against cool ambient sky, realistic shadow depth, gentle light spill and bounce. No harsh flash look, no artificial brightness, no daytime feel.
Textures and surfaces: Preserve real-world micro-details with appropriate night-photography grain — fine, uniform, film-like noise characteristic of high-ISO full-frame sensors (ISO 1600–6400). No plastic smoothing, no noise-free synthetic look, no over-processed NR.
Color science: Professional night color grading — deep rich blues in shadows, warm amber/tungsten in artificial light sources, neutral midtones, accurate skin tones under mixed lighting. Natural saturation, cinematic contrast curve with preserved shadow detail. No crushed blacks, no fake HDR, no neon color cast.
Final quality: The image must look like a carefully planned professional night shoot with premium gear on a perfectly leveled tripod. If the framing feels crooked or it resembles a phone photo, it is incorrect.` },
  { id: 'neblina-montanha', name: 'Neblina da montanha', tag: 'Cinematográfico',
    desc: 'Cria o clima cinematográfico e dramático de um retiro nas montanhas com neblina. Frio, elegante e misterioso.',
    demo: { before: 'foto-original.webp', after: STOCK.neblina },
    accent: '#647A7A',
    askCleanup: true,
    prompt: `CRITICAL — PRESERVE ORIGINAL SCENE: Do not add, remove, modify, or alter any structural or physical element of the original image. Do not add mountains, hills, trees, vegetation, buildings, terrain, horizon lines, or any background elements that are not already present. Do not change the composition, perspective, framing, or geometry. The architecture, furniture, objects, landscape, and spatial layout must remain 100% identical to the original. Only lighting, atmosphere, color, and surface conditions may be altered.
Professional architectural editorial photography. Apply atmospheric and lighting enhancements only.
Atmosphere & Mood: Introduce soft, natural mist and fog only within the existing scene — drifting subtly through the air, softening the existing background elements already visible in the original image. The mist must not generate new landscape features, new depth planes, or new scenery. It should read as humidity and atmospheric haze present in the air of the original environment, nothing more. Cinematic, moody afternoon around 4:00 PM. Stillness, depth, quiet sophistication — the mood of an architectural magazine editorial.
Lighting: Replace any overcast, rainy, or flat lighting with soft diffused afternoon light consistent with a misty environment. Gentle directional shadows, realistic light falloff, low contrast. No sun flares, no harsh highlights. Any sky visible in the original image should read as soft, desaturated, and atmospheric — but the sky area, window shapes, and openings must remain exactly where they are in the original.
Wet Surfaces: If the ground, pavement, deck, driveway, or any outdoor surface appears wet from rain, make it appear naturally dry while preserving the original texture and material. No reflective puddles, no glossy surfaces.
Color & White Balance: Neutral, cinematic palette. Slightly cool with muted warm accents — desaturated greens, soft grays, natural wood tones, earthy shadows. White balance approximately 4800–5200K. No color casts, no artificial saturation. Editorial and restrained.
Texture & Camera Character: Final image must read as captured with a professional full-frame cinema or medium-format camera with a high-end lens — never a phone. Preserve fine grain, natural optical rendering, and micro-contrast typical of professional architectural photography. No plastic smoothness, no HDR halos, no AI-rendered texture.
Technical Corrections:
Remove motion blur and camera shake; restore sharpness
Correct chromatic aberration on edges
Natural sharpening on architectural details and textures
Subtle HDR tone mapping: recover shadow and highlight detail, clean and filmic
No halos, no oversaturation, no "HDR look"
Privacy: Blur any visible license plates realistically. Remove any people present with seamless background reconstruction (using only the existing background — no invented elements).
Style Reference: International editorial architecture photography — Dwell, Architectural Digest, Wallpaper*, Cereal Magazine. Moody, atmospheric, restrained, cinematic. The final image should feel like a still from a high-end architectural film, captured on a misty mountain afternoon with professional equipment — not AI-edited.` },
  { id: 'ultra-realismo', name: 'Ultra realismo', tag: 'Aprimoramento',
    desc: 'Otimiza a nitidez e a resolução óptica perfeitamente sem alterar absolutamente nada na cena original.',
    demo: { before: 'foto-original.webp', after: STOCK.ultra },
    accent: '#4A5B6C',
    askCleanup: true,
    prompt: `Enhance the image to true live-action quality, preserving full realism and photographic authenticity. The result must look like a real filmed scene, never artificial or AI-generated.
Strictly preserve the subject’s identity, anatomy, proportions, expression, and pose. Do not alter who they are or what they are doing. Preserve the exact scene, composition, framing, perspective, and spatial relationships.
Keep the original environment exactly the same. No background changes, no replacements, no added or removed elements. Maintain physical realism with correct scale, depth, gravity, and material behavior.
Recreate the image as if captured with a high-end professional cinema or full-frame camera. Natural optical behavior only: realistic depth of field, lens compression, focus fall-off, and edge softness. No digital or synthetic sharpness.
Match the original lighting direction, angle, intensity, color temperature, and mood. Refine it into a natural cinematic live-action look with soft motivated light, realistic shadows, smooth gradients, controlled contrast, and natural highlight roll-off. No harsh or theatrical lighting.
Preserve real-world textures and micro-details: natural skin texture, fabric weave, surface imperfections, and material realism. No plastic skin, no beauty retouching, no CGI-like surfaces.
Apply professional live-action color science with neutral white balance, cinematic contrast curve, natural saturation, and accurate skin tones. No fake HDR look, no neon colors, no crushed blacks.
Enhance clarity and resolution naturally without altering content. Clean film-grade sharpness only. No halos, no over-processing.
The final image must be indistinguishable from real live-action photography or cinema footage. If it looks generated, stylized, or artificial, it is incorrect.` }
];

const SAMPLE_GALLERY = [
  { id: 'g1', title: 'Sala — Casa da Praia', preset: 'Manhã de sol',  date: '2 dias atrás', img: STOCK.livingRoomBright, imgBefore: STOCK.livingRoomDim, listing: 'Chalé Trancoso' },
  { id: 'g2', title: 'Fachada — Vista mar',   preset: 'Entardecer',    date: '2 dias atrás', img: STOCK.exteriorSunny, imgBefore: STOCK.exterior, listing: 'Chalé Trancoso' },
  { id: 'g3', title: 'Cozinha aberta',         preset: 'HDR editorial', date: '5 dias atrás', img: STOCK.kitchenBright, imgBefore: STOCK.kitchen, listing: 'Loft Vila Madalena' },
  { id: 'g4', title: 'Jantar ao entardecer',   preset: 'Noite aconchegante', date: '1 semana', img: STOCK.diningNight, imgBefore: STOCK.diningDark, listing: 'Loft Vila Madalena' },
  { id: 'g5', title: 'Suíte principal',         preset: 'Manhã de sol', date: '1 semana', img: STOCK.bedroomBright, imgBefore: STOCK.bedroomDim, listing: 'Apto Ipanema 302' },
  { id: 'g6', title: 'Varanda do quarto',      preset: 'Entardecer',    date: '2 semanas', img: STOCK.balcony, imgBefore: STOCK.balcony, listing: 'Apto Ipanema 302' },
  { id: 'g7', title: 'Piscina — manhã',        preset: 'HDR editorial', date: '2 semanas', img: STOCK.pool, imgBefore: STOCK.pool, listing: 'Chalé Trancoso' },
];

const PLANS = [
  { id: 'essencial', name: 'Essencial', price: 57, credits: 15,
    features: ['15 créditos (15 fotos)', 'Todas as predefinições', 'Download em alta', 'Créditos não expiram', 'Suporte por e-mail'] },
  { id: 'profissional', name: 'Profissional', price: 87, credits: 30, featured: true,
    features: ['30 créditos (30 fotos)', 'Todas as predefinições', 'Lote de até 10 fotos', 'Créditos não expiram', 'Histórico ilimitado', 'Suporte prioritário'] },
  { id: 'estudio', name: 'Estúdio', price: 127, credits: 50,
    features: ['50 créditos (50 fotos)', 'Predefinições personalizadas', 'Lote ilimitado', 'Créditos não expiram', 'Relatórios de uso', 'Suporte prioritário'] },
];

// window.USER é populado pelo db.jsx via loadSession() (async). Começa null.
if (typeof window.USER === 'undefined') window.USER = null;

const CLEANUP_PROMPT = `ADDITIONAL INSTRUCTIONS - CLEANUP:

Along with the atmospheric and lighting changes described above, please perform a full cleanup of the scene:

REMOVE:
- All people, guests, or human figures
- Clutter, personal items, and mess (clothes, bags, toiletries, food, dishes, papers)
- Trash, garbage bags, or waste bins visible
- Temporary objects that don't belong to the décor (chargers, bottles, toys)

PRESERVE:
- All furniture, fixtures, and architectural elements
- Original perspective, angle, and framing
- Décor items that are intentional (plants, artwork, cushions, lamps)

FILL removed areas with:
          - Realistic background matching the surrounding environment
- Consistent lighting and texture matching the newly requested atmosphere.`;

const SCREENSHOT_PROMPT = `CRITICAL PRE-PROCESSING RULE — SCREENSHOT / UI OVERLAYS / BLACK BARS (HIGHEST PRIORITY, MUST BE OBEYED):

This image may be a phone or app screenshot. It may contain:
(a) app UI overlays — status bar, navigation bar, buttons, icons, captions, watermarks, timestamps, share sheets, play controls;
(b) black bars, letterbox bars, pillarbox bars, or empty/solid-color margins on the top, bottom, left, or right edges;
(c) rounded corners or notches from the device.

YOU MUST:
1. REMOVE every UI overlay listed in (a) by seamlessly reconstructing the photographic scene that lies beneath it — as if the overlay was never there. Do NOT leave any trace of text, icons, or widgets.
2. FILL every black/empty bar or margin listed in (b) by OUTPAINTING — naturally extending the existing photographic scene outward into those areas so the full frame is occupied by coherent, realistic photographic content. Match perspective, vanishing lines, lighting direction, color grade, texture, grain, and materials of the existing image. The extension must look like it was always part of the original photo — not a patch, not a blur, not a gradient, not a solid color.
3. PRESERVE the original output canvas size and aspect ratio of the input exactly. The final image MUST have the same dimensions as the input. DO NOT crop. DO NOT shrink. DO NOT pad with black. DO NOT change the aspect ratio. DO NOT letterbox the result.
4. PRESERVE the underlying photo's geometry, perspective, proportions, horizon line, and composition exactly (overlay-only edits — no geometric transforms on the real photo content).

FORBIDDEN OUTPUTS (any of these = failure):
- Any remaining black bar, colored bar, or empty margin on any edge.
- A cropped result that is smaller than the input or has a different aspect ratio.
- UI elements, text, icons, or watermarks still visible.
- Visible seams, blur lines, or repetition where the outpainted area meets the original.

If you are unsure whether an edge region is photographic scene or a black bar, treat it as a black bar and outpaint it. The final deliverable must look like a full-frame photograph with zero screenshot artifacts.`;

Object.assign(window, { STOCK, PRESETS, SAMPLE_GALLERY, PLANS, USER, CLEANUP_PROMPT, SCREENSHOT_PROMPT });
