<create-room-modal>
  <div class="modal-overlay" onclick={handleOverlayClick}>
    <div class="modal" onclick={e => e.stopPropagation()}>
      <div class="modal-header">
        <h3>Create New Room</h3>
        <button class="btn btn-ghost btn-icon" onclick={props.cbClose}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>

      <form onsubmit={handleSubmit}>
        <div class="form-group">
          <label for="room-name">Room Name</label>
          <input
            type="text"
            id="room-name"
            placeholder="e.g., Project Discussion"
            value={state.name}
            oninput={e => update({ name: e.target.value })}
            required
          />
        </div>

        <div class="form-group model-picker-group">
          <label>AI Model</label>
          <div class="model-picker-selected" onclick={toggleModelPicker}>
            <span class="model-selected-name">
              {getSelectedModelName()}
            </span>
            <svg class={'model-chevron ' + (state.showPicker ? 'open' : '')} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"/>
            </svg>
          </div>

          <div if={state.showPicker} class="model-picker-dropdown">
            <div class="model-search-wrap">
              <svg class="model-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
              </svg>
              <input
                type="text"
                class="model-search"
                placeholder="Search models..."
                value={state.modelSearch}
                oninput={handleModelSearch}
                ref="modelSearchInput"
              />
            </div>
            <div class="model-list">
              <div if={state.loadingModels} class="model-list-loading">
                Loading models...
              </div>
              <div if={!state.loadingModels && filteredModels().length === 0} class="model-list-empty">
                No models found
              </div>
              <div
                each={model in filteredModels()}
                key={model.id}
                class={'model-option ' + (model.id === state.model_id ? 'selected' : '')}
                onclick={() => selectModel(model)}
              >
                <div class="model-option-name">{model.name}</div>
                <div class="model-option-meta">
                  <span class="model-option-id">{model.id}</span>
                  <span if={model.context_length} class="model-option-ctx">{formatCtx(model.context_length)}</span>
                  <span if={model.supports_vision} class="model-option-vision" title="Supports image input">👁 Vision</span>
                </div>
              </div>
            </div>
          </div>
          <span class="help-text">Choose the AI model that powers this room</span>
        </div>

        <div class="form-group">
          <label class="checkbox-label">
            <input
              type="checkbox"
              checked={state.ai_always_respond}
              onchange={e => update({ ai_always_respond: e.target.checked })}
            />
            <span>AI responds to every message</span>
          </label>
          <span class="help-text">When off, mention @ai to trigger a response</span>
        </div>

        <div class="form-group">
          <label for="system-prompt">System Prompt</label>
          <textarea
            id="system-prompt"
            rows="3"
            placeholder="Instructions for the AI..."
            value={state.system_prompt}
            oninput={e => update({ system_prompt: e.target.value })}
          ></textarea>
        </div>

        <div class="form-group">
          <label for="ai-name">AI Agent Name</label>
          <input
            type="text"
            id="ai-name"
            placeholder="e.g., Nova, Atlas, Sage..."
            value={state.ai_name}
            oninput={e => update({ ai_name: e.target.value })}
            maxlength="20"
          />
          <span class="help-text">The AI's display name in this room</span>
        </div>

        <div class="modal-actions">
          <button type="button" class="btn btn-ghost" onclick={props.cbClose}>Cancel</button>
          <button type="submit" class="btn btn-primary">Create Room</button>
        </div>
      </form>
    </div>
  </div>

  <style>
    .modal-overlay {
      position: fixed;
      inset: 0;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 100;
      animation: fadeIn 0.15s ease;
    }

    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }

    .modal {
      width: 100%;
      max-width: 480px;
      background: var(--bg-secondary);
      border: 1px solid var(--border);
      border-radius: var(--radius-lg);
      padding: var(--space-lg);
      animation: slideUp 0.2s ease;
      max-height: 90vh;
      overflow-y: auto;
    }

    @keyframes slideUp {
      from { transform: translateY(16px); opacity: 0; }
      to { transform: translateY(0); opacity: 1; }
    }

    .modal-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: var(--space-lg);
    }

    .modal-header h3 {
      font-size: var(--text-lg);
      font-weight: 600;
    }

    .btn-icon {
      width: 36px;
      height: 36px;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--radius-md);
    }

    .form-group {
      margin-bottom: var(--space-md);
    }

    .form-group label {
      display: block;
      margin-bottom: var(--space-xs);
      font-size: var(--text-sm);
      color: var(--text-secondary);
    }

    .help-text {
      display: block;
      margin-top: var(--space-xs);
      font-size: var(--text-xs);
      color: var(--text-muted);
    }

    .checkbox-label {
      display: flex !important;
      align-items: center;
      gap: var(--space-sm);
      cursor: pointer;
    }

    .checkbox-label input[type="checkbox"] {
      width: auto;
      accent-color: var(--accent);
    }

    .checkbox-label span {
      color: var(--text-primary);
    }

    textarea {
      min-height: 80px;
    }

    .modal-actions {
      display: flex;
      justify-content: flex-end;
      gap: var(--space-sm);
      margin-top: var(--space-lg);
    }

    /* Model picker */
    .model-picker-group {
      position: relative;
    }

    .model-picker-selected {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: var(--space-sm) var(--space-md);
      background: var(--bg-primary);
      border: 1px solid var(--border);
      border-radius: var(--radius-md);
      cursor: pointer;
      transition: border-color 0.15s;
    }

    .model-picker-selected:hover {
      border-color: var(--accent);
    }

    .model-selected-name {
      font-size: var(--text-sm);
      color: var(--text-primary);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .model-chevron {
      flex-shrink: 0;
      color: var(--text-muted);
      transition: transform 0.15s;
    }

    .model-chevron.open {
      transform: rotate(180deg);
    }

    .model-picker-dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      margin-top: 4px;
      background: var(--bg-secondary);
      border: 1px solid var(--border);
      border-radius: var(--radius-md);
      z-index: 50;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
      overflow: hidden;
    }

    .model-search-wrap {
      position: relative;
      padding: var(--space-sm);
      border-bottom: 1px solid var(--border);
    }

    .model-search-icon {
      position: absolute;
      left: calc(var(--space-sm) + 10px);
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-muted);
      pointer-events: none;
    }

    .model-search {
      width: 100%;
      padding-left: 32px !important;
      font-size: var(--text-sm) !important;
      background: var(--bg-primary) !important;
    }

    .model-list {
      max-height: 260px;
      overflow-y: auto;
    }

    .model-list-loading,
    .model-list-empty {
      padding: var(--space-md);
      text-align: center;
      color: var(--text-muted);
      font-size: var(--text-sm);
    }

    .model-option {
      padding: var(--space-sm) var(--space-md);
      cursor: pointer;
      transition: background 0.1s;
      border-bottom: 1px solid var(--border-subtle, rgba(255,255,255,0.04));
    }

    .model-option:hover {
      background: var(--bg-hover);
    }

    .model-option.selected {
      background: var(--bg-elevated);
      border-left: 2px solid var(--accent);
    }

    .model-option-name {
      font-size: var(--text-sm);
      color: var(--text-primary);
      font-weight: 500;
      margin-bottom: 1px;
    }

    .model-option-meta {
      display: flex;
      align-items: center;
      gap: var(--space-sm);
      font-size: 11px;
      color: var(--text-muted);
    }

    .model-option-id {
      opacity: 0.7;
    }

    .model-option-ctx {
      background: var(--bg-tertiary);
      padding: 1px 5px;
      border-radius: var(--radius-sm);
    }

    .model-option-vision {
      background: rgba(99, 102, 241, 0.15);
      color: var(--accent);
      padding: 1px 6px;
      border-radius: var(--radius-sm);
      font-size: 10px;
      font-weight: 500;
    }
  </style>

  <script>
    import { api } from '../services/api.js'

    export default {
      state: {
        name: '',
        model_id: 'anthropic/claude-sonnet-4',
        ai_always_respond: false,
        system_prompt: 'You are a helpful AI assistant participating in a group chat. Be conversational, helpful, and concise.',
        ai_name: '',
        models: [],
        loadingModels: true,
        showPicker: false,
        modelSearch: '',
      },

      onMounted() {
        const aiNames = ['Nova', 'Atlas', 'Sage', 'Echo', 'Pixel', 'Cosmo', 'Ember', 'Flux', 'Lyra', 'Onyx']
        this.update({ ai_name: aiNames[Math.floor(Math.random() * aiNames.length)] })
        this.fetchModels()
        // Close picker on outside click
        this._onDocClick = (e) => {
          if (this.state.showPicker && !this.$('.model-picker-group')?.contains(e.target)) {
            this.update({ showPicker: false })
          }
        }
        document.addEventListener('click', this._onDocClick)
      },

      onUnmounted() {
        document.removeEventListener('click', this._onDocClick)
      },

      async fetchModels() {
        try {
          const models = await api.listModels()
          this.update({ models, loadingModels: false })
        } catch (err) {
          console.error('Failed to fetch models:', err)
          // Fall back to a small default list
          this.update({
            loadingModels: false,
            models: [
              { id: 'anthropic/claude-sonnet-4', name: 'Claude Sonnet 4', context_length: 200000 },
              { id: 'openai/gpt-4o', name: 'GPT-4o', context_length: 128000 },
              { id: 'google/gemini-2.0-flash-001', name: 'Gemini 2.0 Flash', context_length: 1048576 },
            ],
          })
        }
      },

      toggleModelPicker(e) {
        e.stopPropagation()
        const opening = !this.state.showPicker
        this.update({ showPicker: opening, modelSearch: '' })
        if (opening) {
          setTimeout(() => this.$('.model-search')?.focus(), 50)
        }
      },

      handleModelSearch(e) {
        this.update({ modelSearch: e.target.value })
      },

      selectModel(model) {
        this.update({ model_id: model.id, showPicker: false, modelSearch: '' })
      },

      filteredModels() {
        const q = this.state.modelSearch.toLowerCase().trim()
        if (!q) return this.state.models
        return this.state.models.filter(
          (m) => m.name.toLowerCase().includes(q) || m.id.toLowerCase().includes(q)
        )
      },

      getSelectedModelName() {
        const m = this.state.models.find((m) => m.id === this.state.model_id)
        return m ? m.name : this.state.model_id
      },

      formatCtx(n) {
        if (!n) return ''
        if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M ctx'
        if (n >= 1000) return Math.round(n / 1000) + 'K ctx'
        return n + ' ctx'
      },

      handleOverlayClick() {
        this.props.cbClose()
      },

      handleSubmit(e) {
        e.preventDefault()
        this.props.cbCreate({
          name: this.state.name,
          model_id: this.state.model_id,
          ai_always_respond: this.state.ai_always_respond,
          system_prompt: this.state.system_prompt,
          ai_name: this.state.ai_name,
        })
      },
    }
  </script>
</create-room-modal>
