{% extends "base.html" %}
{% block content %}

<div class="page-header">
  <div>
    <div class="page-title">// <span>settings</span></div>
    <div class="page-subtitle">~/.scrylo/config.yaml</div>
  </div>
</div>

<style>
  .settings-section-title {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    color: var(--text-faint);
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 1rem;
    padding-bottom: 0.6rem;
    border-bottom: 1px solid var(--border);
  }
  .field-label {
    display: block;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    color: var(--text-dim);
    letter-spacing: 0.06em;
    margin-bottom: 0.4rem;
  }
  .field-hint {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    color: var(--text-faint);
    margin-top: 0.35rem;
    line-height: 1.65;
  }
  .settings-input {
    width: 100%;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 0.58rem 0.85rem;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.75rem;
    color: var(--text-body);
    outline: none;
    transition: border-color 0.15s;
  }
  .settings-input:focus { border-color: var(--accent-ring); }
  .settings-input::placeholder { color: var(--text-invisible); }
  .badge-optional {
    display: inline-block;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.54rem;
    color: var(--text-faint);
    border: 1px solid var(--border);
    border-radius: 3px;
    padding: 0.08rem 0.38rem;
    margin-left: 0.45rem;
    letter-spacing: 0.06em;
    vertical-align: middle;
    text-transform: uppercase;
  }
  .badge-ok {
    display: inline-block;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.54rem;
    color: var(--green);
    border: 1px solid rgba(74,222,128,0.22);
    border-radius: 3px;
    padding: 0.08rem 0.38rem;
    margin-left: 0.45rem;
    letter-spacing: 0.06em;
    vertical-align: middle;
    text-transform: uppercase;
  }
  .key-card {
    padding: 1rem 1.1rem;
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 6px;
    margin-bottom: 1rem;
  }
</style>

<div style="padding:2rem;max-width:740px;">
  
  {% if request.query_params.get('saved') %}
    <div style="padding:0.65rem 1rem;background:rgba(34,197,94,0.08);border:1px solid rgba(34,197,94,0.2);border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:#22c55e;margin-bottom:1rem;">
      ✓ Config saved to ~/.scrylo/config.yaml
    </div>
  {% elif request.query_params.get('error') %}
    <div style="padding:0.65rem 1rem;background:rgba(244,63,94,0.08);border:1px solid rgba(244,63,94,0.2);border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:#f43f5e;margin-bottom:1rem;">
      ✗ Error: {{ request.query_params.get('error') }}
    </div>
  {% endif %}

  <form method="POST" action="/settings/save">

    <!-- ── SMTP ── -->
    <div style="margin-bottom:2.5rem;">
      <div class="settings-section-title">// smtp · email sending</div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
        <div>
          <label class="field-label">SMTP Host</label>
          <input class="settings-input" type="text" name="smtp_host"
                 id="smtpHost"
                 list="smtp-hosts-list"
                 value="{{ cfg.email.smtp_host }}"
                 placeholder="smtp.gmail.com"
                 oninput="autoFillPort(this.value)"/>
          <datalist id="smtp-hosts-list">
            <option value="smtp.gmail.com"      data-port="587">Gmail</option>
            <option value="smtp-mail.outlook.com" data-port="587">Outlook / Hotmail</option>
            <option value="smtp.mail.yahoo.com"  data-port="587">Yahoo Mail</option>
            <option value="smtp.zoho.com"        data-port="587">Zoho Mail</option>
            <option value="smtp-relay.brevo.com" data-port="587">Brevo (Sendinblue)</option>
            <option value="smtp.mailgun.org"     data-port="587">Mailgun</option>
            <option value="smtp.sendgrid.net"    data-port="587">SendGrid</option>
            <option value="email-smtp.us-east-1.amazonaws.com" data-port="587">AWS SES</option>
          </datalist>
        </div>
        <div>
          <label class="field-label">SMTP Port</label>
          <input class="settings-input" type="text" name="smtp_port" value="{{ cfg.email.smtp_port }}" placeholder="587"/>
        </div>
        <div>
          <label class="field-label">SMTP User</label>
          <input class="settings-input" type="text" name="smtp_user" value="{{ cfg.email.smtp_user }}" placeholder="you@gmail.com"/>
        </div>
        <div>
          <label class="field-label">SMTP Password</label>
          <input class="settings-input" type="password" name="smtp_password" value="" placeholder="••••••••"/>
          <div class="field-hint" style="margin-top:0.4rem;">
            <span style="color:var(--accent);">Gmail/Outlook users:</span> your account password won't work here — you need an <strong style="color:var(--text-body);">App Password</strong>.<br>
            Gmail → <a href="https://myaccount.google.com/apppasswords" target="_blank" style="color:var(--accent);">myaccount.google.com/apppasswords</a> (requires 2FA) ·
            Outlook → <a href="https://account.live.com/proofs/apppassword" target="_blank" style="color:var(--accent);">account.live.com/proofs/apppassword</a><br>
            <span style="color:var(--green);">Recommended:</span> use <strong style="color:var(--text-body);">Zoho Mail</strong> or <strong style="color:var(--text-body);">Brevo</strong> on a custom domain — plain password works, better deliverability.
          </div>
        </div>
        <div>
          <label class="field-label">From Name</label>
          <input class="settings-input" type="text" name="from_name" value="{{ cfg.email.from_name }}" placeholder="Your Name"/>
        </div>
        <div>
          <label class="field-label">From Address</label>
          <input class="settings-input" type="text" name="from_address" value="{{ cfg.email.from_address }}" placeholder="you@yourdomain.com"/>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;margin-top:1rem;">
        <div>
          <label class="field-label">Daily Send Limit</label>
          <input class="settings-input" type="text" name="daily_send_limit" value="{{ cfg.email.daily_send_limit }}" placeholder="50"/>
        </div>
        <div>
          <label class="field-label">Min Delay (sec)</label>
          <input class="settings-input" type="text" name="min_delay_seconds" value="{{ cfg.email.min_delay_seconds }}" placeholder="90"/>
        </div>
        <div>
          <label class="field-label">Max Delay (sec)</label>
          <input class="settings-input" type="text" name="max_delay_seconds" value="{{ cfg.email.max_delay_seconds }}" placeholder="180"/>
        </div>
      </div>
    </div>

    <!-- ── LLM ── -->
    <div style="margin-bottom:2.5rem;">
      <div class="settings-section-title">// llm · pitch generation</div>

      <!-- LLM chain status -->
      <div style="background:var(--card);border:1px solid var(--border);border-radius:6px;padding:1rem;margin-bottom:1.25rem;font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--text-faint);line-height:1.8;">
        <span style="color:var(--text-muted);">Pitch chain:</span>
        {% if cfg.llm.groq_api_key|default('') %}
          <span style="color:var(--green);">Groq (active)</span> → Ollama → smart templates
        {% else %}
          <span style="color:var(--text-faint);">Groq (no key)</span> → Ollama → <span style="color:var(--accent);">smart templates (active)</span>
        {% endif %}
      </div>

      <!-- Groq key -->
      <div class="key-card">
        <label class="field-label">
          Groq API Key
          <span class="badge-optional">optional</span>
          {% if cfg.llm.groq_api_key|default('') %}<span class="badge-ok">✓ active</span>{% endif %}
        </label>
        <input class="settings-input" type="text" name="groq_api_key"
               value="{{ cfg.llm.groq_api_key|default('') }}"
               placeholder="gsk_... — get a free key at console.groq.com"/>
        <div class="field-hint">
          {% if cfg.llm.groq_api_key|default('') %}
            <span style="color:var(--green);">Using Llama 3.3 70B for pitches · Llama 3.1 8B for parsing</span>
          {% else %}
            Recommended. Free, any email, no credit card —
            <a href="https://console.groq.com" target="_blank" style="color:var(--accent);">console.groq.com</a>.
            Without it, Scrylo falls back to Jinja2 smart templates.
          {% endif %}
        </div>
      </div>

      <!-- Ollama status -->
      <div class="key-card" style="margin-top:1rem;">
        <label class="field-label">
          Ollama Status
          {% if ollama_active %}
            <span class="badge-ok">✓ connected</span>
          {% else %}
            <span style="background:rgba(248,113,113,0.1);color:#f87171;font-size:0.55rem;padding:0.15rem 0.45rem;border-radius:4px;font-weight:700;">✗ not detected</span>
          {% endif %}
        </label>
        <div class="field-hint">
          {% if ollama_active %}
            {% if ollama_models %}
              <div style="color:var(--green);margin-bottom:0.4rem;">Pulled models found:</div>
              <div style="display:flex;flex-wrap:wrap;gap:0.4rem;">
                {% for m in ollama_models %}
                  <span style="background:rgba(255,255,255,0.05);border:1px solid var(--border);padding:0.15rem 0.4rem;border-radius:4px;font-size:0.6rem;color:var(--text-body);">{{ m }}</span>
                {% endfor %}
              </div>
            {% else %}
              <span style="color:var(--accent);">Ollama is running but no models are pulled.</span><br/>
              Run <code style="background:rgba(0,0,0,0.3);padding:0.1rem 0.3rem;border-radius:3px;">ollama pull llama3.2</code> in your terminal to enable local AI pitches.
            {% endif %}
          {% else %}
            Scrylo checks for Ollama on <code style="background:rgba(0,0,0,0.3);padding:0.1rem 0.3rem;border-radius:3px;">localhost:11434</code>. 
            Used as an automatic fallback if no Groq key is set.
          {% endif %}
        </div>
      </div>

      <!-- Ollama settings (power users) -->
      <details>
        <summary style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);cursor:pointer;padding:0.35rem 0;user-select:none;">
          // ollama settings (power users)
        </summary>
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;margin-top:0.85rem;">
          <div>
            <label class="field-label">n_ctx</label>
            <input class="settings-input" type="text" name="n_ctx" value="{{ cfg.llm.n_ctx }}" placeholder="2048"/>
          </div>
          <div>
            <label class="field-label">n_threads</label>
            <input class="settings-input" type="text" name="n_threads" value="{{ cfg.llm.n_threads }}" placeholder="4"/>
          </div>
          <div>
            <label class="field-label">Temperature</label>
            <input class="settings-input" type="text" name="temperature" value="{{ cfg.llm.temperature }}" placeholder="0.7"/>
          </div>
        </div>
      </details>
    </div>

    <!-- ── DISCOVERY ENGINE / SOURCES ── -->
    <div style="margin-bottom:2.5rem;" id="scraper">
      <div class="settings-section-title">// lead engine · discovery</div>


      <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem;">
        <div>
          <label class="field-label">Max Parallel Requests</label>
          <input class="settings-input" type="text" name="max_parallel_requests" value="{{ cfg.scraper.max_parallel_requests }}" placeholder="10"/>
        </div>
        <div>
          <label class="field-label">Rate Limit Delay (sec)</label>
          <input class="settings-input" type="text" name="rate_limit_delay" value="{{ cfg.scraper.rate_limit_delay }}" placeholder="1.5"/>
        </div>
      </div>

      <!-- Serper — optional, web search only -->
      <div class="key-card">
        <label class="field-label">
          Serper API Key
          <span class="badge-optional">optional</span>
          {% if cfg.scraper.serper_api_key %}<span class="badge-ok">✓ active</span>{% endif %}
        </label>
        <input class="settings-input" type="text" name="serper_api_key"
               value="{{ cfg.scraper.serper_api_key }}"
               placeholder="Paste key from serper.dev — 2,500 free searches/month"/>
        <div class="field-hint">
          Only required for the <span style="color:var(--text-body);">🌐 Web Search</span> source.
          <span style="color:var(--text-body);">🐙 GitHub</span> works with no API key at all.
          Free key at <a href="https://serper.dev" target="_blank" style="color:var(--accent);">serper.dev</a>.
        </div>
      </div>

      <!-- GitHub token — optional, just improves rate limits -->
      <div class="key-card" style="margin-bottom:0;">
        <label class="field-label">
          GitHub Token
          <span class="badge-optional">optional</span>
          {% if cfg.scraper.github_token|default('') %}<span class="badge-ok">✓ active</span>{% endif %}
        </label>
        <input class="settings-input" type="text" name="github_token"
               value="{{ cfg.scraper.github_token|default('') }}"
               placeholder="ghp_... — raises rate limit from 60 → 5,000 req/hr"/>
        <div class="field-hint">
          GitHub search works without this — but large searches may hit the 60 req/hr unauthenticated limit.
          Create a token with no scopes at
          <a href="https://github.com/settings/tokens" target="_blank" style="color:var(--accent);">github.com/settings/tokens</a>.
        </div>
      </div>
    </div>

    <!-- ── PITCH / SERVICE ── -->
    <div style="margin-bottom:2.5rem;">
      <div class="settings-section-title">// pitch · your service</div>
      <div class="key-card" style="margin-bottom:0;">
        <label class="field-label">
          Service Description
          <span class="badge-optional">recommended</span>
          {% if cfg.pitch.service_description|default('') %}<span class="badge-ok">✓ configured</span>{% endif %}
        </label>
        <textarea class="settings-input" name="service_description" rows="4"
                  style="resize:vertical;line-height:1.65;"
                  placeholder='e.g. "We build automated outbound email pipelines for B2B SaaS companies. We help sales teams book 3x more meetings without extra headcount."'>{{ cfg.pitch.service_description|default('') }}</textarea>
        <div class="field-hint">
          Tell the AI what you actually sell. The more specific, the better the pitch.
          {% if not cfg.pitch.service_description|default('') %}
            <span style="color:var(--accent);">⚠ Without this, pitches will be generic — the AI won't know what to offer.</span>
          {% else %}
            <span style="color:var(--green);">Used in every generated pitch to personalise the value proposition.</span>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- ── ICP SCORING ── -->
    <div style="margin-bottom:2.5rem;">
      <div class="settings-section-title">// icp · ideal customer profile</div>
      <div class="key-card" style="margin-bottom:0;">
        <label class="field-label">
          ICP Profile
          <span class="badge-optional">optional</span>
          {% if cfg.icp.profile|default('') %}<span class="badge-ok">✓ configured</span>{% endif %}
        </label>
        <textarea class="settings-input" name="icp_profile" rows="3"
                  style="resize:vertical;line-height:1.65;"
                  placeholder='e.g. "B2B SaaS founder or CEO, company 1–50 employees, English-speaking market, selling to SMBs"'>{{ cfg.icp.profile|default('') }}</textarea>
        <div class="field-hint">
          Used by the ICP scorer to rank leads after discovery. Plain English — describe your ideal prospect's role, company size, industry, and location.
          {% if not cfg.icp.profile|default('') %}
            <span style="color:var(--text-dim);">Without this, ICP scoring is disabled.</span>
          {% else %}
            <span style="color:var(--green);">MiniLM similarity scoring active · falls back to keyword matching if not installed.</span>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- ── COMPLIANCE ── -->
    <div style="margin-bottom:2.5rem;">
      <div class="settings-section-title">// compliance · can-spam / gdpr</div>
      <div>
        <label class="field-label">Physical Address <span style="color:var(--text-faint);font-size:0.57rem;font-weight:400;">(required by CAN-SPAM — appears in all outgoing emails)</span></label>
        <input class="settings-input" type="text" name="physical_address"
               value="{{ cfg.compliance.physical_address }}" placeholder="123 Main St, City, State ZIP"/>
      </div>
    </div>

    <!-- Save -->
    <div style="display:flex;align-items:center;gap:1rem;">
      <button type="submit" style="
        background:var(--accent);color:#0b0a08;
        font-family:'Bricolage Grotesque',sans-serif;font-size:0.88rem;font-weight:700;
        padding:0.65rem 1.75rem;border:none;border-radius:6px;
        cursor:pointer;transition:all 0.18s;
      "
      onmouseover="this.style.background='#fbbf24';this.style.transform='translateY(-1px)'"
      onmouseout="this.style.background='var(--accent)';this.style.transform='none'">
        Save settings →
      </button>
      <span class="htmx-indicator" style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-dim);">saving...</span>
    </div>

  </form>
</div>

<script>
const _SMTP_PORTS = {
  "smtp.gmail.com":              587,
  "smtp-mail.outlook.com":       587,
  "smtp.mail.yahoo.com":         587,
  "smtp.zoho.com":               587,
  "smtp-relay.brevo.com":        587,
  "smtp.mailgun.org":            587,
  "smtp.sendgrid.net":           587,
  "email-smtp.us-east-1.amazonaws.com": 587,
};
function autoFillPort(host) {
  const port = _SMTP_PORTS[host.trim()];
  if (port) document.querySelector('[name="smtp_port"]').value = port;
}
// Auto-fill on page load if host already set
window.addEventListener('DOMContentLoaded', () => {
  const h = document.getElementById('smtpHost');
  if (h && h.value) autoFillPort(h.value);
});
</script>

{% endblock %}
