All files / web/src/app/admin/page-spots page.tsx

0% Statements 0/909
0% Branches 0/1
0% Functions 0/1
0% Lines 0/909

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use client'

import { useCallback, useState } from 'react'
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
import { css } from '../../../../styled-system/css'
import { AppNavBar } from '@/components/AppNavBar'
import { AdminNav } from '@/components/AdminNav'
import { useBackgroundTask } from '@/hooks/useBackgroundTask'
import { ContentSpot } from '@/components/page-spots/ContentSpot'
import { pageSpotKeys } from '@/lib/queryKeys'
import type { SpotConfig } from '@/lib/page-spots/types'

// ---------------------------------------------------------------------------
// Types for the status API response
// ---------------------------------------------------------------------------

interface SpotStatus {
  id: string
  label: string
  description: string
  aspectRatio: string | null
  config: SpotConfig | null
  imageUrl: string | null
  imageSizeBytes?: number
  htmlExists: boolean
}

interface PageStatus {
  pageId: string
  label: string
  spots: SpotStatus[]
}

interface ProviderInfo {
  id: string
  name: string
  available: boolean
  models: Array<{ id: string; name: string }>
}

interface StatusResponse {
  pages: PageStatus[]
  providers: ProviderInfo[]
  components: Array<{ id: string; label: string; description: string }>
}

// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------

const segmentBtnStyle = (active: boolean) =>
  css({
    backgroundColor: active ? '#30363d' : 'transparent',
    color: active ? '#f0f6fc' : '#8b949e',
    border: '1px solid #30363d',
    borderRadius: '0',
    padding: '3px 12px',
    fontSize: '11px',
    fontWeight: '600',
    cursor: 'pointer',
    '&:first-of-type': { borderRadius: '6px 0 0 6px' },
    '&:last-of-type': { borderRadius: '0 6px 6px 0' },
    '&:hover': { color: '#c9d1d9' },
  })

const smallBtnStyle = css({
  backgroundColor: '#21262d',
  color: '#c9d1d9',
  border: '1px solid #30363d',
  borderRadius: '6px',
  padding: '4px 12px',
  fontSize: '12px',
  fontWeight: '600',
  cursor: 'pointer',
  '&:hover': { backgroundColor: '#30363d' },
  '&:disabled': { opacity: 0.5, cursor: 'not-allowed' },
})

const primaryBtnStyle = css({
  backgroundColor: '#238636',
  color: '#ffffff',
  border: '1px solid #2ea043',
  borderRadius: '6px',
  padding: '4px 12px',
  fontSize: '12px',
  fontWeight: '600',
  cursor: 'pointer',
  '&:hover': { backgroundColor: '#2ea043' },
  '&:disabled': { opacity: 0.5, cursor: 'not-allowed' },
})

const inputStyle = css({
  backgroundColor: '#0d1117',
  color: '#c9d1d9',
  border: '1px solid #30363d',
  borderRadius: '6px',
  padding: '6px 10px',
  fontSize: '13px',
  width: '100%',
  '&:focus': { outline: 'none', borderColor: '#58a6ff' },
})

const selectStyle = css({
  backgroundColor: '#0d1117',
  color: '#c9d1d9',
  border: '1px solid #30363d',
  borderRadius: '6px',
  padding: '6px 10px',
  fontSize: '13px',
  '&:focus': { outline: 'none', borderColor: '#58a6ff' },
})

const cardStyle = css({
  backgroundColor: '#161b22',
  border: '1px solid #30363d',
  borderRadius: '8px',
  padding: '16px',
  marginBottom: '12px',
})

const labelStyle = css({
  fontSize: '11px',
  color: '#8b949e',
  fontWeight: '600',
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
  marginBottom: '4px',
})

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------

export default function PageSpotsAdmin() {
  const queryClient = useQueryClient()
  const [activePageId, setActivePageId] = useState<string>('home')

  const { data, isLoading } = useQuery<StatusResponse>({
    queryKey: pageSpotKeys.status(),
    queryFn: async () => {
      const res = await fetch('/api/admin/page-spots/status')
      if (!res.ok) throw new Error('Failed to fetch status')
      return res.json()
    },
  })

  const activePage = data?.pages.find((p) => p.pageId === activePageId)

  return (
    <div
      data-component="page-spots-admin"
      className={css({ minHeight: '100vh', backgroundColor: '#0d1117' })}
    >
      <AppNavBar />
      <div className={css({ paddingTop: '56px' })}>
        <AdminNav />
      </div>
      <div className={css({ maxWidth: '1200px', margin: '0 auto', padding: '24px' })}>
        <h1
          className={css({
            fontSize: '20px',
            fontWeight: '600',
            color: '#f0f6fc',
            marginBottom: '16px',
          })}
        >
          Page Content Spots
        </h1>

        {isLoading && <div className={css({ color: '#8b949e', padding: '24px' })}>Loading...</div>}

        {data && (
          <>
            {/* Page tabs */}
            <div className={css({ display: 'flex', gap: '4px', marginBottom: '20px' })}>
              {data.pages.map((page) => (
                <button
                  key={page.pageId}
                  onClick={() => setActivePageId(page.pageId)}
                  className={segmentBtnStyle(page.pageId === activePageId)}
                >
                  {page.label}
                </button>
              ))}
            </div>

            {/* Spots for active page */}
            {activePage?.spots.map((spot) => (
              <SpotCard
                key={spot.id}
                pageId={activePageId}
                spot={spot}
                providers={data.providers}
                components={data.components}
                onRefresh={() => queryClient.invalidateQueries({ queryKey: pageSpotKeys.status() })}
              />
            ))}
          </>
        )}
      </div>
    </div>
  )
}

// ---------------------------------------------------------------------------
// SpotCard
// ---------------------------------------------------------------------------

function SpotCard({
  pageId,
  spot,
  providers,
  components,
  onRefresh,
}: {
  pageId: string
  spot: SpotStatus
  providers: ProviderInfo[]
  components: Array<{ id: string; label: string; description: string }>
  onRefresh: () => void
}) {
  const spotType = spot.config?.type ?? null
  const [pendingType, setPendingType] = useState<string | null>(null)
  const activeType = pendingType ?? spotType

  const setTypeMutation = useMutation({
    mutationFn: async (type: string) => {
      let config: SpotConfig
      if (type === 'generated') {
        config = { type: 'generated', prompt: '' }
      } else if (type === 'component') {
        config = { type: 'component', componentId: components[0]?.id ?? '' }
      } else {
        config = { type: 'html' }
      }
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spot.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      })
      if (!res.ok) throw new Error('Failed to update')
      return res.json()
    },
    onSuccess: () => {
      setPendingType(null)
      onRefresh()
    },
  })

  const handleTypeChange = (type: string) => {
    if (type === spotType) return
    setPendingType(type)
    setTypeMutation.mutate(type)
  }

  return (
    <div className={cardStyle} data-element="spot-card">
      <div
        className={css({
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'flex-start',
          marginBottom: '12px',
        })}
      >
        <div>
          <div className={css({ fontSize: '15px', fontWeight: '600', color: '#f0f6fc' })}>
            {spot.label}
          </div>
          <div className={css({ fontSize: '12px', color: '#8b949e' })}>
            {spot.description}
            {spot.aspectRatio && <span> &middot; {spot.aspectRatio}</span>}
          </div>
        </div>

        {/* Type selector */}
        <div className={css({ display: 'flex' })}>
          {(['generated', 'component', 'html'] as const).map((type) => (
            <button
              key={type}
              onClick={() => handleTypeChange(type)}
              className={segmentBtnStyle(activeType === type)}
              disabled={setTypeMutation.isPending}
            >
              {type.charAt(0).toUpperCase() + type.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {/* Type-specific editor */}
      {spot.config?.type === 'generated' && (
        <GeneratedSpotEditor
          pageId={pageId}
          spotId={spot.id}
          config={spot.config}
          imageUrl={spot.imageUrl}
          imageSizeBytes={spot.imageSizeBytes}
          providers={providers}
          aspectRatio={spot.aspectRatio}
          onRefresh={onRefresh}
        />
      )}

      {spot.config?.type === 'component' && (
        <ComponentSpotEditor
          pageId={pageId}
          spotId={spot.id}
          config={spot.config}
          components={components}
          aspectRatio={spot.aspectRatio}
          onRefresh={onRefresh}
        />
      )}

      {spot.config?.type === 'html' && (
        <HtmlSpotEditor
          pageId={pageId}
          spotId={spot.id}
          config={spot.config}
          htmlExists={spot.htmlExists}
          aspectRatio={spot.aspectRatio}
          onRefresh={onRefresh}
        />
      )}

      {!spot.config && (
        <div className={css({ color: '#8b949e', fontSize: '13px', fontStyle: 'italic' })}>
          Select a type above to configure this spot.
        </div>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// Generated Spot Editor
// ---------------------------------------------------------------------------

function GeneratedSpotEditor({
  pageId,
  spotId,
  config,
  imageUrl,
  imageSizeBytes,
  providers,
  aspectRatio,
  onRefresh,
}: {
  pageId: string
  spotId: string
  config: {
    type: 'generated'
    prompt: string
    provider?: 'gemini' | 'openai'
    model?: string
    focalPoint?: { x: number; y: number }
  }
  imageUrl: string | null
  imageSizeBytes?: number
  providers: ProviderInfo[]
  aspectRatio: string | null
  onRefresh: () => void
}) {
  const [prompt, setPrompt] = useState(config.prompt)
  const [provider, setProvider] = useState(
    config.provider ?? providers.find((p) => p.available)?.id ?? ''
  )
  const [model, setModel] = useState(config.model ?? '')
  const [taskId, setTaskId] = useState<string | null>(null)
  const [focalX, setFocalX] = useState(config.focalPoint?.x ?? 50)
  const [focalY, setFocalY] = useState(config.focalPoint?.y ?? 50)

  const selectedProvider = providers.find((p) => p.id === provider)
  const availableModels = selectedProvider?.models ?? []

  // Auto-select first model if none selected
  if (!model && availableModels.length > 0) {
    setModel(availableModels[0].id)
  }

  const task = useBackgroundTask(taskId)

  const saveConfigMutation = useMutation({
    mutationFn: async (updatedConfig: SpotConfig) => {
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedConfig),
      })
      if (!res.ok) throw new Error('Failed to save')
      return res.json()
    },
    onSuccess: () => onRefresh(),
  })

  const generateMutation = useMutation({
    mutationFn: async () => {
      // Save config first
      await saveConfigMutation.mutateAsync({
        type: 'generated',
        prompt,
        provider: provider as 'gemini' | 'openai',
        model,
        focalPoint: { x: focalX, y: focalY },
      })

      const res = await fetch('/api/admin/page-spots/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pageId, spotId, provider, model, forceRegenerate: true }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data.error || 'Failed to start generation')
      }
      return res.json()
    },
    onSuccess: (data) => {
      setTaskId(data.taskId)
    },
  })

  const refineMutation = useMutation({
    mutationFn: async () => {
      // Save current prompt first
      await saveConfigMutation.mutateAsync({
        type: 'generated',
        prompt,
        provider: provider as 'gemini' | 'openai',
        model,
        focalPoint: { x: focalX, y: focalY },
      })

      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}/refine-prompt`, {
        method: 'POST',
      })
      if (!res.ok) throw new Error('Failed to refine')
      return res.json()
    },
    onSuccess: (data) => {
      if (data.refined) {
        setPrompt(data.refined)
      }
    },
  })

  const handleSave = useCallback(() => {
    saveConfigMutation.mutate({
      type: 'generated',
      prompt,
      provider: provider as 'gemini' | 'openai',
      model,
      focalPoint: { x: focalX, y: focalY },
    })
  }, [prompt, provider, model, focalX, focalY, saveConfigMutation])

  const isGenerating = task.state?.status === 'pending' || task.state?.status === 'running'

  // Auto-refresh on task completion
  if (task.state?.status === 'completed' && taskId) {
    setTaskId(null)
    onRefresh()
  }

  return (
    <div className={css({ display: 'flex', flexDirection: 'column', gap: '12px' })}>
      {/* Prompt */}
      <div>
        <div className={labelStyle}>Prompt</div>
        <textarea
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          rows={3}
          className={css({
            backgroundColor: '#0d1117',
            color: '#c9d1d9',
            border: '1px solid #30363d',
            borderRadius: '6px',
            padding: '8px 10px',
            fontSize: '13px',
            width: '100%',
            resize: 'vertical',
            fontFamily: 'inherit',
            '&:focus': { outline: 'none', borderColor: '#58a6ff' },
          })}
        />
        <div className={css({ display: 'flex', gap: '8px', marginTop: '6px' })}>
          <button
            onClick={handleSave}
            className={smallBtnStyle}
            disabled={saveConfigMutation.isPending}
          >
            {saveConfigMutation.isPending ? 'Saving...' : 'Save'}
          </button>
          <button
            onClick={() => refineMutation.mutate()}
            className={smallBtnStyle}
            disabled={refineMutation.isPending || !prompt}
          >
            {refineMutation.isPending ? 'Refining...' : 'Refine with AI'}
          </button>
        </div>
      </div>

      {/* Provider / Model */}
      <div className={css({ display: 'flex', gap: '12px' })}>
        <div className={css({ flex: 1 })}>
          <div className={labelStyle}>Provider</div>
          <select
            value={provider}
            onChange={(e) => {
              setProvider(e.target.value)
              setModel('')
            }}
            className={selectStyle}
          >
            {providers.map((p) => (
              <option key={p.id} value={p.id} disabled={!p.available}>
                {p.name} {!p.available && '(no key)'}
              </option>
            ))}
          </select>
        </div>
        <div className={css({ flex: 1 })}>
          <div className={labelStyle}>Model</div>
          <select value={model} onChange={(e) => setModel(e.target.value)} className={selectStyle}>
            {availableModels.map((m) => (
              <option key={m.id} value={m.id}>
                {m.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Focal point */}
      <div className={css({ display: 'flex', gap: '12px' })}>
        <div className={css({ flex: 1 })}>
          <div className={labelStyle}>Focal X (%)</div>
          <input
            type="number"
            min={0}
            max={100}
            value={focalX}
            onChange={(e) => setFocalX(Number(e.target.value))}
            className={inputStyle}
          />
        </div>
        <div className={css({ flex: 1 })}>
          <div className={labelStyle}>Focal Y (%)</div>
          <input
            type="number"
            min={0}
            max={100}
            value={focalY}
            onChange={(e) => setFocalY(Number(e.target.value))}
            className={inputStyle}
          />
        </div>
      </div>

      {/* Generate button */}
      <div>
        <button
          onClick={() => generateMutation.mutate()}
          className={primaryBtnStyle}
          disabled={isGenerating || !prompt || !provider || !model}
        >
          {isGenerating
            ? `Generating... ${task.state?.progress ?? 0}%`
            : generateMutation.isPending
              ? 'Starting...'
              : 'Generate Image'}
        </button>
        {generateMutation.isError && (
          <div className={css({ color: '#f85149', fontSize: '12px', marginTop: '4px' })}>
            {generateMutation.error.message}
          </div>
        )}
        {task.state?.status === 'failed' && (
          <div className={css({ color: '#f85149', fontSize: '12px', marginTop: '4px' })}>
            Generation failed: {task.state.error}
          </div>
        )}
      </div>

      {/* Preview */}
      {imageUrl && (
        <div>
          <div className={labelStyle}>
            Preview {imageSizeBytes ? `(${formatBytes(imageSizeBytes)})` : ''}
          </div>
          <div
            className={css({
              maxWidth: '400px',
              borderRadius: '6px',
              overflow: 'hidden',
              border: '1px solid #30363d',
            })}
          >
            <ContentSpot
              config={config}
              aspectRatio={aspectRatio ?? undefined}
              imageUrl={imageUrl}
            />
          </div>
        </div>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// Component Spot Editor
// ---------------------------------------------------------------------------

function ComponentSpotEditor({
  pageId,
  spotId,
  config,
  components,
  aspectRatio,
  onRefresh,
}: {
  pageId: string
  spotId: string
  config: { type: 'component'; componentId: string }
  components: Array<{ id: string; label: string; description: string }>
  aspectRatio: string | null
  onRefresh: () => void
}) {
  const [componentId, setComponentId] = useState(config.componentId)

  const saveMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'component', componentId: id }),
      })
      if (!res.ok) throw new Error('Failed to save')
      return res.json()
    },
    onSuccess: () => onRefresh(),
  })

  return (
    <div className={css({ display: 'flex', flexDirection: 'column', gap: '12px' })}>
      <div>
        <div className={labelStyle}>Component</div>
        <div className={css({ display: 'flex', gap: '8px' })}>
          <select
            value={componentId}
            onChange={(e) => {
              setComponentId(e.target.value)
              saveMutation.mutate(e.target.value)
            }}
            className={selectStyle}
          >
            {components.map((c) => (
              <option key={c.id} value={c.id}>
                {c.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Live preview */}
      {componentId && (
        <div>
          <div className={labelStyle}>Preview</div>
          <div
            className={css({
              maxWidth: '400px',
              borderRadius: '6px',
              overflow: 'hidden',
              border: '1px solid #30363d',
            })}
          >
            <ContentSpot
              config={{ type: 'component', componentId }}
              aspectRatio={aspectRatio ?? undefined}
            />
          </div>
        </div>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// HTML Spot Editor
// ---------------------------------------------------------------------------

function HtmlSpotEditor({
  pageId,
  spotId,
  config,
  htmlExists,
  aspectRatio,
  onRefresh,
}: {
  pageId: string
  spotId: string
  config: {
    type: 'html'
    captureUrl?: string
    captureMethod?: string
    captureBody?: unknown
    captureExtractPath?: string
  }
  htmlExists: boolean
  aspectRatio: string | null
  onRefresh: () => void
}) {
  const [html, setHtml] = useState('')
  const [htmlLoaded, setHtmlLoaded] = useState(false)
  const [captureUrl, setCaptureUrl] = useState(config.captureUrl ?? '')
  const [captureMethod, setCaptureMethod] = useState(config.captureMethod ?? 'GET')
  const [captureExtractPath, setCaptureExtractPath] = useState(config.captureExtractPath ?? '')

  const queryClient = useQueryClient()

  // Load HTML on first mount
  const htmlQuery = useQuery({
    queryKey: pageSpotKeys.html(pageId, spotId),
    queryFn: async () => {
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}/html`)
      if (!res.ok) throw new Error('Failed to load HTML')
      const data = await res.json()
      return data.html as string | null
    },
    enabled: !htmlLoaded,
  })

  if (htmlQuery.data !== undefined && !htmlLoaded) {
    setHtml(htmlQuery.data ?? '')
    setHtmlLoaded(true)
  }

  const saveHtmlMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}/html`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ html }),
      })
      if (!res.ok) throw new Error('Failed to save')
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: pageSpotKeys.html(pageId, spotId) })
      onRefresh()
    },
  })

  const saveConfigMutation = useMutation({
    mutationFn: async () => {
      const updatedConfig: SpotConfig = {
        type: 'html',
        ...(captureUrl ? { captureUrl } : {}),
        ...(captureMethod !== 'GET' ? { captureMethod: captureMethod as 'GET' | 'POST' } : {}),
        ...(captureExtractPath ? { captureExtractPath } : {}),
      }
      const res = await fetch(`/api/admin/page-spots/${pageId}/${spotId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedConfig),
      })
      if (!res.ok) throw new Error('Failed to save config')
      return res.json()
    },
    onSuccess: () => onRefresh(),
  })

  const captureMutation = useMutation({
    mutationFn: async () => {
      // Save config with capture URL first
      await saveConfigMutation.mutateAsync()

      const res = await fetch('/api/admin/page-spots/capture-snapshot', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          pageId,
          spotId,
          url: captureUrl,
          method: captureMethod,
          extractPath: captureExtractPath || undefined,
        }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data.error || 'Capture failed')
      }
      return res.json()
    },
    onSuccess: () => {
      setHtmlLoaded(false) // reload
      queryClient.invalidateQueries({ queryKey: pageSpotKeys.html(pageId, spotId) })
      onRefresh()
    },
  })

  return (
    <div className={css({ display: 'flex', flexDirection: 'column', gap: '12px' })}>
      {/* HTML textarea */}
      <div>
        <div className={labelStyle}>HTML Content</div>
        <textarea
          value={html}
          onChange={(e) => setHtml(e.target.value)}
          rows={6}
          className={css({
            backgroundColor: '#0d1117',
            color: '#c9d1d9',
            border: '1px solid #30363d',
            borderRadius: '6px',
            padding: '8px 10px',
            fontSize: '12px',
            width: '100%',
            resize: 'vertical',
            fontFamily: 'monospace',
            '&:focus': { outline: 'none', borderColor: '#58a6ff' },
          })}
        />
        <button
          onClick={() => saveHtmlMutation.mutate()}
          className={smallBtnStyle}
          style={{ marginTop: '6px' }}
          disabled={saveHtmlMutation.isPending}
        >
          {saveHtmlMutation.isPending ? 'Saving...' : 'Save HTML'}
        </button>
      </div>

      {/* URL capture */}
      <div className={css({ borderTop: '1px solid #21262d', paddingTop: '12px' })}>
        <div className={labelStyle}>Capture from URL</div>
        <div className={css({ display: 'flex', gap: '8px', marginBottom: '6px' })}>
          <select
            value={captureMethod}
            onChange={(e) => setCaptureMethod(e.target.value)}
            className={selectStyle}
            style={{ width: '80px' }}
          >
            <option value="GET">GET</option>
            <option value="POST">POST</option>
          </select>
          <input
            value={captureUrl}
            onChange={(e) => setCaptureUrl(e.target.value)}
            placeholder="/api/some/endpoint"
            className={inputStyle}
          />
        </div>
        <div className={css({ marginBottom: '6px' })}>
          <input
            value={captureExtractPath}
            onChange={(e) => setCaptureExtractPath(e.target.value)}
            placeholder="extractPath (e.g. pages.0)"
            className={inputStyle}
          />
        </div>
        <button
          onClick={() => captureMutation.mutate()}
          className={smallBtnStyle}
          disabled={captureMutation.isPending || !captureUrl}
        >
          {captureMutation.isPending ? 'Capturing...' : 'Capture'}
        </button>
        {captureMutation.isError && (
          <div className={css({ color: '#f85149', fontSize: '12px', marginTop: '4px' })}>
            {captureMutation.error.message}
          </div>
        )}
      </div>

      {/* Preview */}
      {htmlLoaded && html && (
        <div>
          <div className={labelStyle}>Preview</div>
          <div
            className={css({
              maxWidth: '400px',
              borderRadius: '6px',
              overflow: 'hidden',
              border: '1px solid #30363d',
            })}
          >
            <ContentSpot
              config={{ type: 'html' }}
              aspectRatio={aspectRatio ?? undefined}
              html={html}
            />
          </div>
        </div>
      )}
    </div>
  )
}