@if (predictionMode) {
  <app-timesfm-prediction />
} @else {
  <main id="top" class="research-terminal" [class.bangla-copy]="language() === 'bn'">
    <header class="topbar">
      <a class="brand" href="#top" aria-label="DSE research home">
        <span class="brand-mark">D</span>
        <span class="brand-copy">
          <strong>DOHA RESEARCH</strong>
          <small>DSE · MULTI-AGENT DOSSIER</small>
        </span>
      </a>

      <div class="topbar-actions">
        <label class="stock-selector">
          <span>{{ language() === 'bn' ? 'কোম্পানি' : 'Company' }}</span>
          <select
            [(ngModel)]="selectedSymbol"
            [disabled]="loadingStocks()"
            (change)="selectStock()"
            aria-label="Choose a DSE company"
          >
            @for (stock of stocks(); track stock.symbol) {
              <option [value]="stock.symbol">{{ stock.symbol }} · {{ stock.name }}</option>
            }
          </select>
        </label>

        <button
          class="primary-action"
          type="button"
          [disabled]="loadingAnalysis()"
          (click)="runAnalysis(false)"
        >
          @if (loadingAnalysis()) { <span class="button-spinner"></span> }
          <span>{{ language() === 'bn' ? 'নতুন বিশ্লেষণ' : 'Run new analysis' }}</span>
        </button>

        <div class="language-switch" role="group" aria-label="Report language">
          <button type="button" [class.active]="language() === 'en'" (click)="setLanguage('en')">EN</button>
          <button type="button" [class.active]="language() === 'bn'" (click)="setLanguage('bn')">বাং</button>
        </div>
      </div>
    </header>

    @if (loadingAnalysis() && analysis()) {
      <div class="progress-notice" aria-live="polite">
        <span class="progress-pulse"></span>
        <strong>{{ language() === 'bn' ? 'নতুন প্রতিবেদন তৈরি হচ্ছে' : 'Building a fresh report' }}</strong>
        <span>{{ jobMessage() || (language() === 'bn' ? 'এজেন্টরা প্রমাণ পর্যালোচনা করছে…' : 'Agents are reviewing the evidence…') }}</span>
      </div>
    }

    @if (loadingAnalysis() && !analysis()) {
      <section class="loading-state" aria-live="polite">
        <div class="loading-orbit"><i></i><span>D</span></div>
        <p class="eyebrow">MULTI-AGENT RESEARCH IN PROGRESS</p>
        <h1>{{ language() === 'bn' ? 'প্রমাণ থেকে বিনিয়োগ সিদ্ধান্ত তৈরি হচ্ছে' : 'Turning evidence into an investment decision' }}</h1>
        <p>{{ jobMessage() || (language() === 'bn' ? 'ডিএসই তথ্য লোড হচ্ছে…' : 'Loading verified DSE evidence…') }}</p>
        <div class="loading-steps" aria-hidden="true">
          <span class="active">Market</span><i></i><span>Fundamentals</span><i></i><span>Debate</span><i></i><span>Risk</span><i></i><span>Decision</span>
        </div>
      </section>
    }

    @if (errorMessage() && !analysis()) {
      <section class="empty-state" aria-live="polite">
        <span class="state-icon">!</span>
        <p class="eyebrow">REPORT NOT AVAILABLE</p>
        <h1>{{ language() === 'bn' ? 'এই কোম্পানির বিশ্লেষণ এখনও প্রস্তুত নয়' : 'No completed dossier for this company yet' }}</h1>
        <p>{{ errorMessage() }}</p>
        <button class="primary-action" type="button" (click)="runAnalysis(false)">
          {{ language() === 'bn' ? 'এখন বিশ্লেষণ চালান' : 'Run the full analysis' }}
        </button>
      </section>
    }

    @if (analysis(); as report) {
      <section class="report-hero" [class]="decisionTone(report)">
        <div class="hero-main">
          <div class="hero-meta">
            <span class="sector-chip">{{ report.sector || 'DSE Equity' }}</span>
            <span class="date-chip">{{ report.analysis_date | date: 'mediumDate' }}</span>
            @if (report.ai_research) { <span class="verified-chip"><i>✓</i> AI GROUNDED</span> }
          </div>

          <p class="eyebrow">INVESTMENT RESEARCH DOSSIER</p>
          <h1>{{ report.company_name }}</h1>
          <div class="symbol-line">
            <strong>{{ report.symbol }}</strong>
            <span>Dhaka Stock Exchange</span>
            <span>Generated {{ report.generated_at | date: 'medium' }}</span>
          </div>

          <div class="decision-block">
            <div class="decision-copy">
              <span class="decision-kicker">{{ language() === 'bn' ? 'চূড়ান্ত অবস্থান' : 'FINAL POSITION' }}</span>
              <strong>{{ finalDecision(report) }}</strong>
              <small>{{ hasAgentEvidence(report) ? 'Portfolio Manager · final multi-agent authority' : report.ai_research ? copy(report.ai_research.trader_report.action) : copy(report.score_label) }}</small>
            </div>
            <span class="decision-mark" aria-hidden="true">
              {{ decisionTone(report) === 'positive' ? '✓' : decisionTone(report) === 'negative' ? '×' : '!' }}
            </span>
          </div>
        </div>

        <aside class="hero-score-card">
          <div class="score-chart">
            <canvas #scoreCanvas aria-label="Fundamental score"></canvas>
            <div class="score-center">
              <strong>{{ report.fundamental_score }}</strong>
              <span>/100</span>
            </div>
          </div>
          <div class="score-copy">
            <span>{{ report.ai_research ? (language() === 'bn' ? 'এআই মৌলিক স্কোর' : 'AI fundamental score') : (language() === 'bn' ? 'মৌলিক স্কোর' : 'Fundamental score') }}</span>
            <strong>{{ copy(report.score_label) }}</strong>
            <small>{{ report.ai_research ? (report.ai_research.score_confidence | titlecase) + ' confidence' : 'Deterministic DSE evidence' }}</small>
          </div>
        </aside>
      </section>

      <section class="market-ribbon" aria-label="Market snapshot">
        <div class="price-cell">
          <span>{{ language() === 'bn' ? 'সর্বশেষ মূল্য' : 'Latest price' }}</span>
          <strong>{{ formatTaka(report.market.latest_price) }}</strong>
          @if (report.market.change_percent !== null) {
            <small [class.positive-text]="report.market.change_percent > 0" [class.negative-text]="report.market.change_percent < 0">
              {{ report.market.change_percent > 0 ? '▲' : report.market.change_percent < 0 ? '▼' : '•' }}
              {{ signedPercent(report.market.change_percent) }} today
            </small>
          }
        </div>
        <div>
          <span>{{ language() === 'bn' ? 'পূর্ববর্তী ক্লোজ' : 'Previous close' }}</span>
          <strong>{{ formatTaka(report.market.previous_close) }}</strong>
        </div>
        <div>
          <span>52W low</span>
          <strong>{{ formatTaka(report.market.fifty_two_week_low) }}</strong>
        </div>
        <div class="range-cell">
          <div><span>52-week position</span><strong>{{ rangePosition(report) | number: '1.0-0' }}%</strong></div>
          <div class="mini-range"><i [style.left.%]="rangePosition(report)"></i></div>
          <small><span>Low</span><span>High</span></small>
        </div>
        <div>
          <span>52W high</span>
          <strong>{{ formatTaka(report.market.fifty_two_week_high) }}</strong>
        </div>
      </section>

      <nav class="section-nav" aria-label="Report sections">
        <button type="button" (click)="jumpTo('decision-summary')">01 · Decision</button>
        <button type="button" (click)="jumpTo('valuation')">02 · Valuation</button>
        <button type="button" (click)="jumpTo('factor-scorecard')">03 · Factors</button>
        <button type="button" (click)="jumpTo('research-dossier')">04 · Full dossier</button>
        <span>{{ reportDocumentCount() }} agent documents</span>
      </nav>

      <section id="decision-summary" class="decision-layout section-anchor">
        <article class="investment-case surface-card">
          <header class="section-heading compact">
            <div>
              <p class="eyebrow">01 · DECISION AT A GLANCE</p>
              <h2>{{ copy(report.headline) }}</h2>
            </div>
            <span class="status-badge" [class]="decisionTone(report)">
              <i>{{ decisionTone(report) === 'positive' ? '✓' : decisionTone(report) === 'negative' ? '×' : '!' }}</i>
              {{ finalDecision(report) }}
            </span>
          </header>

          <p class="lead-copy">{{ copy(report.in_depth_snippet) }}</p>
          <div class="takeaway-list">
            @for (takeaway of report.takeaways; track takeaway.en; let index = $index) {
              <div class="takeaway-item">
                <span>{{ (index + 1).toString().padStart(2, '0') }}</span>
                <p>{{ copy(takeaway) }}</p>
              </div>
            }
          </div>

          @if (report.ai_research; as ai) {
            <div class="ai-rationale">
              <div class="ai-rationale-head">
                <span class="ai-badge">AI SYNTHESIS</span>
                <small>{{ ai.provider }} · {{ ai.model }}</small>
              </div>
              <p>{{ copy(ai.score_rationale) }}</p>
              <footer>
                <span>Evidence confidence</span>
                <strong>{{ ai.score_confidence | uppercase }}</strong>
              </footer>
            </div>
          }
        </article>

        <aside class="decision-rail">
          @if (report.ai_research; as ai) {
            <article class="rail-card thesis">
              <span class="rail-icon positive">↗</span>
              <div><small>INVESTMENT THESIS</small><p>{{ copy(ai.trader_report.investment_thesis) }}</p></div>
            </article>
            <article class="rail-card entry">
              <span class="rail-icon caution">→</span>
              <div><small>ENTRY STRATEGY</small><p>{{ copy(ai.trader_report.entry_strategy) }}</p></div>
            </article>
            <article class="rail-card risk">
              <span class="rail-icon negative">↓</span>
              <div><small>RISK CONTROLS</small><p>{{ copy(ai.trader_report.risk_controls) }}</p></div>
            </article>
            <article class="rail-card horizon">
              <span class="rail-icon neutral">◷</span>
              <div><small>TIME HORIZON</small><p>{{ copy(ai.trader_report.time_horizon) }}</p></div>
            </article>
          } @else {
            <article class="rail-card neutral-card">
              <span class="rail-icon neutral">i</span>
              <div><small>REPORT MODE</small><p>This result uses deterministic DSE calculations. The AI trader synthesis is not available for this saved report.</p></div>
            </article>
          }
        </aside>
      </section>

      @if (report.ai_research; as ai) {
        <section class="trigger-grid">
          <article class="trigger-card positive">
            <header><span>+</span><div><p class="eyebrow">WHAT COULD WORK</p><h3>Potential catalysts</h3></div></header>
            <ul>
              @for (item of ai.trader_report.catalysts; track item.en) { <li>{{ copy(item) }}</li> }
            </ul>
          </article>
          <article class="trigger-card negative">
            <header><span>×</span><div><p class="eyebrow">WHEN TO REASSESS</p><h3>Invalidation conditions</h3></div></header>
            <ul>
              @for (item of ai.trader_report.invalidation_conditions; track item.en) { <li>{{ copy(item) }}</li> }
            </ul>
          </article>
        </section>
      }

      <section id="valuation" class="valuation-section section-anchor">
        <header class="section-heading">
          <div>
            <p class="eyebrow">02 · PRICE VS VALUE</p>
            <h2>{{ language() === 'bn' ? 'দামের পেছনে মূল্য কতটা শক্ত?' : 'What does the price imply?' }}</h2>
            <p>{{ copy(report.valuation.summary) }}</p>
          </div>
          <span class="valuation-verdict" [class]="report.valuation.verdict">{{ copy(report.valuation.verdict_label) }}</span>
        </header>

        <div class="valuation-board surface-card">
          <div class="valuation-numbers">
            <div><span>CURRENT PRICE</span><strong>{{ formatTaka(report.valuation.current_price) }}</strong></div>
            <div><span>ROUGH FAIR VALUE</span><strong>{{ formatTaka(report.valuation.rough_estimate) }}</strong></div>
            <div>
              <span>ESTIMATE GAP</span>
              <strong [class.positive-text]="(fairValueGap(report) ?? 0) > 0" [class.negative-text]="(fairValueGap(report) ?? 0) < 0">
                {{ fairValueGap(report) === null ? '—' : signedPercent(fairValueGap(report)) }}
              </strong>
            </div>
            <div><span>CONFIDENCE</span><strong>{{ report.valuation.confidence | titlecase }}</strong></div>
          </div>

          @if (report.valuation.fair_range_low !== null && report.valuation.fair_range_high !== null) {
            <div class="valuation-range">
              <div class="range-label-row"><span>Relative value map</span><small>Not a price target</small></div>
              <div class="value-track">
                <span class="fair-zone" [style.left.%]="valuationScale(report).low" [style.width.%]="valuationScale(report).high - valuationScale(report).low"></span>
                <i class="current-marker" [style.left.%]="valuationScale(report).current"><b>Current</b></i>
              </div>
              <div class="value-track-labels">
                <span [style.left.%]="valuationScale(report).low">{{ formatTaka(report.valuation.fair_range_low) }}</span>
                <span [style.left.%]="valuationScale(report).high">{{ formatTaka(report.valuation.fair_range_high) }}</span>
              </div>
            </div>
          }

          <div class="valuation-methods">
            @for (method of report.valuation.methods; track method.key) {
              <article [class.unavailable]="!method.available">
                <span [class.available]="method.available">{{ method.available ? '✓' : '—' }}</span>
                <div><small>{{ copy(method.label) }}</small><strong>{{ formatTaka(method.value) }}</strong></div>
              </article>
            }
          </div>
          <p class="method-note">These are educational estimates calculated from available DSE evidence. They are not guaranteed values or instructions to trade.</p>
        </div>
      </section>

      <section id="factor-scorecard" class="factor-section section-anchor">
        <header class="section-heading">
          <div>
            <p class="eyebrow">03 · EVIDENCE SCORECARD</p>
            <h2>{{ language() === 'bn' ? 'কোন বিষয় শক্ত, কোনটিতে সতর্কতা?' : 'Where the evidence is strong—and where it is not' }}</h2>
            <p>Green supports the case, amber requires monitoring, and red deserves investigation before capital is committed.</p>
          </div>
          <div class="status-legend" aria-label="Signal legend">
            <span class="positive"><i>✓</i> Positive</span>
            <span class="caution"><i>!</i> Watch</span>
            <span class="negative"><i>×</i> Concern</span>
          </div>
        </header>

        <div class="factor-grid">
          @for (factor of report.factors; track factor.key) {
            <article class="factor-card" [class]="factor.status">
              <header>
                <div class="factor-mark"><span>{{ factor.status === 'positive' ? '✓' : factor.status === 'negative' ? '×' : factor.status === 'caution' ? '!' : '•' }}</span></div>
                <div><p>{{ copy(factor.subtitle) }}</p><h3>{{ copy(factor.title) }}</h3></div>
                <strong>{{ factorAverage(report, factor.key) | number: '1.0-1' }}<small>/10</small></strong>
              </header>
              <p class="factor-explanation">{{ copy(factor.explanation) }}</p>
              <div class="factor-metrics">
                @for (metric of factor.metrics; track metric.key) {
                  <div class="factor-metric">
                    <div><span>{{ copy(metric.label) }}</span><strong>{{ metric.display_value }}</strong></div>
                    <div class="metric-track"><i [class]="metricStatus(metric.score)" [style.width.%]="metric.score * 10"></i></div>
                    <small>{{ metric.score | number: '1.0-1' }}/10</small>
                  </div>
                }
              </div>
              <footer><span class="status-badge" [class]="factor.status"><i>{{ factor.status === 'positive' ? '✓' : factor.status === 'negative' ? '×' : '!' }}</i>{{ factorStatus(factor.status) }}</span></footer>
            </article>
          }
        </div>
      </section>

      <section class="summary-reports">
        <header class="section-heading compact">
          <div><p class="eyebrow">DETERMINISTIC SUMMARY</p><h2>{{ copy(report.in_depth_title) }}</h2></div>
        </header>
        <div class="summary-report-grid">
          @for (section of report.report_sections; track section.key) {
            <article [class]="getSectionStatus(section.key)">
              <header><span>{{ getSectionStatus(section.key) === 'positive' ? '✓' : getSectionStatus(section.key) === 'negative' ? '×' : getSectionStatus(section.key) === 'caution' ? '!' : '•' }}</span><h3>{{ copy(section.title) }}</h3></header>
              <p>{{ copy(section.summary) }}</p>
              @if (section.bullets.length) {
                <ul>@for (bullet of section.bullets; track bullet.en) { <li>{{ copy(bullet) }}</li> }</ul>
              }
            </article>
          }
        </div>
      </section>

      <section id="research-dossier" class="dossier-section section-anchor">
        <header class="dossier-heading">
          <div>
            <p class="eyebrow">04 · COMPLETE MULTI-AGENT RECORD</p>
            <h2>Every report. One readable dossier.</h2>
            <p>The CLI’s full analyst, research, trading, risk, and portfolio output is preserved below. Open any document to read its headings, tables, lists, and conclusions in a clean research format.</p>
          </div>
          <div class="dossier-count"><strong>{{ reportDocumentCount() }}</strong><span>documents available</span></div>
        </header>

        @if (reportGroups().length) {
          <div class="dossier-layout">
            <aside class="dossier-index">
              <p>REPORT INDEX</p>
              @for (group of reportGroups(); track group.key; let index = $index) {
                <button type="button" (click)="jumpTo(group.key)"><span>{{ (index + 1).toString().padStart(2, '0') }}</span>{{ group.title }}<small>{{ group.documents.length }}</small></button>
              }
              <button type="button" class="technical-link" (click)="jumpTo('source-ledger')"><span>↳</span>Sources & technical log</button>
            </aside>

            <div class="dossier-content">
              @for (group of reportGroups(); track group.key) {
                <section [id]="group.key" class="report-group section-anchor">
                  <header>
                    <p class="eyebrow">{{ group.kicker }}</p>
                    <h3>{{ group.title }}</h3>
                    <p>{{ group.description }}</p>
                  </header>

                  <div class="document-stack" [class.debate-documents]="group.key === 'research-debate'">
                    @for (document of group.documents; track document.key) {
                      <details class="report-document" [class]="document.tone" [open]="document.open">
                        <summary>
                          <span class="document-avatar">{{ document.icon }}</span>
                          <span class="document-title"><small>{{ document.role }}</small><strong>{{ document.title }}</strong></span>
                          <span class="document-tone" [class]="document.tone">
                            {{ document.tone === 'positive' ? '✓' : document.tone === 'negative' ? '×' : document.tone === 'caution' ? '!' : '•' }}
                          </span>
                          <span class="document-toggle"><i></i></span>
                        </summary>
                        <article class="markdown-report" [innerHTML]="document.html"></article>
                      </details>
                    }
                  </div>
                </section>
              }
            </div>
          </div>
        } @else {
          <div class="no-dossier">
            <span>i</span>
            <div><h3>No multi-agent state was attached to this saved analysis.</h3><p>Run a fresh analysis from the main CLI to populate the complete analyst, debate, risk, and portfolio dossier.</p></div>
          </div>
        }
      </section>

      <section id="source-ledger" class="source-section section-anchor">
        <header class="section-heading compact">
          <div><p class="eyebrow">PROVENANCE & AUDIT</p><h2>Know where every layer came from.</h2></div>
        </header>
        <div class="source-grid">
          @for (source of report.sources; track source.name) {
            <article>
              <span>{{ source.source_type === 'dse_api' ? 'DSE' : source.source_type === 'agent_state' ? 'AI' : source.source_type === 'calculation' ? 'ƒx' : 'LLM' }}</span>
              <div><small>{{ source.source_type.replace('_', ' ') }}</small><h3>{{ source.name }}</h3><p>{{ source.detail }}</p></div>
            </article>
          }
        </div>

        @if (hasAgentEvidence(report)) {
          <details class="technical-state">
            <summary>Developer view · complete JSON state log <span>Open technical record</span></summary>
            <pre>{{ rawState(report) }}</pre>
          </details>
        }
      </section>

      <footer class="report-footer">
        <div class="footer-brand"><span>D</span><strong>DOHA RESEARCH</strong></div>
        <div class="disclaimer"><strong>Important</strong><p>{{ copy(report.disclaimer) }}</p></div>
        <a href="#top">Back to top ↑</a>
      </footer>
    }
  </main>
}
