/**
 * Simulation Shell — Der Rahmen um jede Simulation
 *
 * Enthält:
 * - Header mit Titel und Metadaten
 * - POE-Phase-Indikator (Predict → Observe → Explain)
 * - Variablen-Regler
 * - Canvas-Container für die Visualisierung
 * - Reflexions-Panel
 */

import { Simulation } from '@core/simulation'
import { AUSTRIA, getLocalName } from '@core/education-levels'

export class SimShell {
  private container: HTMLElement
  private sim: Simulation
  private canvasContainer: HTMLElement
  private controlsContainer: HTMLElement

  constructor(hostElement: HTMLElement, sim: Simulation) {
    this.sim = sim
    this.container = document.createElement('div')
    this.container.className = 'sim-shell'
    this.container.innerHTML = this.buildHTML()
    hostElement.appendChild(this.container)

    this.canvasContainer = this.container.querySelector('.sim-canvas-area')!
    this.controlsContainer = this.container.querySelector('.sim-controls')!

    this.buildControls()
    this.updatePhaseUI()
  }

  getCanvasContainer(): HTMLElement {
    return this.canvasContainer
  }

  private buildHTML(): string {
    const m = this.sim.meta
    const localName = getLocalName(AUSTRIA, m.primaryLevel) || `Stufe ${m.primaryLevel}`

    return `
      <style>
        .sim-shell { max-width: 900px; margin: 0 auto; padding: 1rem; }
        .sim-header { margin-bottom: 1rem; }
        .sim-header h2 { font-size: 1.4rem; font-weight: 800; letter-spacing: -.02em; margin-bottom: .2rem; }
        .sim-header-meta { display: flex; gap: .4rem; flex-wrap: wrap; }
        .sim-meta-tag { font-size: .68rem; font-weight: 600; padding: 2px 8px; border-radius: 6px; }
        .sim-meta-klasse { background: #dae8ec; color: #4a7c8a; }
        .sim-meta-zeit { background: #f0eeea; color: #6a6a6a; }
        .sim-meta-typ { background: #dceadd; color: #5a8a5e; }

        .sim-poe { display: flex; gap: .3rem; margin-bottom: 1rem; }
        .sim-poe-step { flex: 1; padding: .5rem; border-radius: 8px; text-align: center; font-size: .72rem; font-weight: 600; background: #f0eeea; color: #8a8a8a; transition: all .3s; }
        .sim-poe-step.active { background: #4a7c8a; color: #fff; }
        .sim-poe-step.done { background: #dceadd; color: #5a8a5e; }

        .sim-body { display: grid; grid-template-columns: 1fr 240px; gap: 1rem; }
        .sim-canvas-area { background: #fff; border-radius: 12px; border: 1px solid rgba(0,0,0,.06); overflow: hidden; min-height: 300px; box-shadow: 0 2px 10px rgba(0,0,0,.04); }
        .sim-sidebar { display: flex; flex-direction: column; gap: .8rem; }

        .sim-controls { background: #fff; border-radius: 12px; border: 1px solid rgba(0,0,0,.06); padding: 1rem; box-shadow: 0 2px 10px rgba(0,0,0,.04); }
        .sim-controls h4 { font-size: .78rem; font-weight: 700; color: #4a7c8a; margin-bottom: .6rem; text-transform: uppercase; letter-spacing: .06em; }
        .sim-control { margin-bottom: .8rem; }
        .sim-control label { display: flex; justify-content: space-between; font-size: .78rem; font-weight: 500; margin-bottom: .2rem; }
        .sim-control label span { color: #8a8a8a; font-weight: 600; }
        .sim-control input[type=range] { width: 100%; -webkit-appearance: none; height: 6px; border-radius: 3px; background: #e8e8e4; outline: none; }
        .sim-control input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%; background: #4a7c8a; cursor: pointer; box-shadow: 0 1px 4px rgba(0,0,0,.15); }

        .sim-lernziele { background: #fff; border-radius: 12px; border: 1px solid rgba(0,0,0,.06); padding: 1rem; box-shadow: 0 2px 10px rgba(0,0,0,.04); }
        .sim-lernziele h4 { font-size: .78rem; font-weight: 700; color: #5a8a5e; margin-bottom: .4rem; }
        .sim-lernziele ul { font-size: .75rem; color: #4a4a4a; padding-left: 1rem; }
        .sim-lernziele li { margin-bottom: .2rem; }

        .sim-phase-btn { width: 100%; padding: .6rem; border: none; border-radius: 8px; font-weight: 600; font-size: .82rem; cursor: pointer; background: #4a7c8a; color: #fff; transition: all .2s; }
        .sim-phase-btn:hover { background: #3a6470; }

        @media (max-width: 700px) {
          .sim-body { grid-template-columns: 1fr; }
        }
      </style>

      <div class="sim-header">
        <h2>${m.name}</h2>
        <div class="sim-header-meta">
          <span class="sim-meta-tag sim-meta-klasse">${localName}</span>
          <span class="sim-meta-tag sim-meta-zeit">⏱ ${m.dpiMinuten} min</span>
          <span class="sim-meta-tag sim-meta-typ">${m.typ}</span>
        </div>
      </div>

      <div class="sim-poe">
        <div class="sim-poe-step" data-phase="intro">📖 Intro</div>
        <div class="sim-poe-step" data-phase="predict">🤔 Predict</div>
        <div class="sim-poe-step" data-phase="simulate">🔬 Simulate</div>
        <div class="sim-poe-step" data-phase="observe">👁️ Observe</div>
        <div class="sim-poe-step" data-phase="reflect">💭 Reflect</div>
      </div>

      <div class="sim-body">
        <div class="sim-canvas-area"></div>
        <div class="sim-sidebar">
          <div class="sim-controls">
            <h4>Parameter</h4>
          </div>
          <div class="sim-lernziele">
            <h4>🎯 Lernziele</h4>
            <ul>${m.lernziele.map(l => `<li>${l}</li>`).join('')}</ul>
          </div>
          <button class="sim-phase-btn" onclick="this.closest('.sim-shell').__nextPhase()">
            Weiter →
          </button>
        </div>
      </div>
    `

    // Attach next phase handler
    setTimeout(() => {
      const btn = this.container.querySelector('.sim-phase-btn') as HTMLButtonElement
      if (btn) {
        btn.addEventListener('click', () => {
          this.sim.nextPhase()
          this.updatePhaseUI()
        })
      }
    }, 0)
  }

  private buildControls(): void {
    const ranges = this.sim.getVariableRanges()
    const ctrl = this.controlsContainer

    for (const [key, range] of Object.entries(ranges)) {
      const div = document.createElement('div')
      div.className = 'sim-control'
      div.innerHTML = `
        <label>${range.label} <span class="val">${range.default}${range.unit ? ' ' + range.unit : ''}</span></label>
        <input type="range" min="${range.min}" max="${range.max}" value="${range.default}" step="${range.max > 10 ? 1 : 0.01}">
      `

      const input = div.querySelector('input')!
      const valSpan = div.querySelector('.val')!

      input.addEventListener('input', () => {
        const v = parseFloat(input.value)
        this.sim.setVariable(key, v)
        valSpan.textContent = `${v}${range.unit ? ' ' + range.unit : ''}`
      })

      ctrl.appendChild(div)
    }
  }

  private updatePhaseUI(): void {
    const phases = ['intro', 'predict', 'simulate', 'observe', 'reflect']
    const current = this.sim['state'].phase  // accessing protected state
    const currentIdx = phases.indexOf(current === 'complete' ? 'reflect' : current)

    this.container.querySelectorAll('.sim-poe-step').forEach((el, i) => {
      el.classList.remove('active', 'done')
      if (i === currentIdx) el.classList.add('active')
      else if (i < currentIdx) el.classList.add('done')
    })
  }
}
