// Self-contained Pebble config page - no server, no companion app. The
// form itself is a `data:` URI built entirely here in pkjs and opened
// via Pebble.openURL(); app_message.c's inbox_received_handler is the
// receiving side this pairs with (see its own comment for the wire
// format - lat/lon/UTC offset cross as scaled int32s since AppMessage
// has no float tuple type).
//
// The webview's own storage can't be relied on to remember values
// between openings (Pebble treats each `data:` URI load as a fresh,
// effectively unique origin), so previously-submitted values are kept
// in *pkjs's* own localStorage (persists across app launches on the
// phone) and baked into the generated HTML each time the page opens.
//
// Plain ES5 throughout (var, string concatenation, no arrow functions/
// template literals) - the webview runs in whatever WebView the Pebble
// mobile app itself embeds, not a guaranteed-modern engine.

var STORAGE_KEY = 'deckInADashConfig';
var LANGUAGES = [
  { code: 'en', label: 'English' },
  { code: 'de', label: 'Deutsch' }
];
// Matches engine/src/tarot.h's Gender enum (GENDER_UNSPECIFIED = 0,
// GENDER_MALE = 1, GENDER_FEMALE = 2) - only affects the Celtic Cross
// position text's pronouns, never the chart/draw itself.
var GENDERS = [
  { code: 0, label: 'Prefer not to say' },
  { code: 1, label: 'Male' },
  { code: 2, label: 'Female' }
];

// 120x120 PNG of res/logo-small.png, inlined as base64 - this page is a
// bare `data:` URI with no server, so there's nowhere else to load an
// image from. Shown in place of a plain text title, matching the app's
// own branding on the one surface this project draws on the phone
// itself (the watch's own launcher icon is a separate, unrelated image -
// see package.json's IMAGE_APP_ICON).
var LOGO_DATA_URI = 'data:image/png;base64,[encoded data, 46580 characters]';

function loadSavedConfig() {
  try {
    var raw = window.localStorage.getItem(STORAGE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {
    // Corrupt/inaccessible storage - fall through to defaults below.
  }
  return {};
}

function saveConfig(cfg) {
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cfg));
  } catch (e) {
    // Best-effort only - the watch already has the real submitted
    // values via AppMessage regardless of whether this cache succeeds.
  }
}

function escapeHtml(value) {
  var s = value === null || value === undefined ? '' : String(value);
  return s.replace(/[&<>"']/g, function (c) {
    return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
  });
}

function buildLanguageOptions(selected) {
  var html = '';
  for (var i = 0; i < LANGUAGES.length; i++) {
    var lang = LANGUAGES[i];
    var isSelected = lang.code === selected ? ' selected' : '';
    html += '<option value="' + lang.code + '"' + isSelected + '>' + lang.label + '</option>';
  }
  return html;
}

function buildGenderOptions(selected) {
  var html = '';
  for (var i = 0; i < GENDERS.length; i++) {
    var gender = GENDERS[i];
    var isSelected = gender.code === selected ? ' selected' : '';
    html += '<option value="' + gender.code + '"' + isSelected + '>' + gender.label + '</option>';
  }
  return html;
}

// Runs *inside* the webview (embedded as a <script> string below), not
// in pkjs's own context - reads the form, validates it, and hands the
// result back to pkjs via the standard Pebble config-page convention:
// navigating to pebblejs://close#<urlencoded JSON>, which fires pkjs's
// own 'webviewclosed' event with that payload as e.response.
var FORM_SCRIPT =
  'document.getElementById("cfg").addEventListener("submit", function (ev) {' +
  '  ev.preventDefault();' +
  '  var errorEl = document.getElementById("error");' +
  '  errorEl.style.display = "none";' +
  '  var birthDate = document.getElementById("birth_date").value;' +
  '  var birthTime = document.getElementById("birth_time").value;' +
  '  var utcOffset = parseFloat(document.getElementById("birth_utc_offset").value);' +
  '  var lat = parseFloat(document.getElementById("birth_lat").value);' +
  '  var lon = parseFloat(document.getElementById("birth_lon").value);' +
  '  var gender = parseInt(document.getElementById("gender").value, 10);' +
  '  var lang = document.getElementById("lang").value;' +
  '  var notifyEnabled = document.getElementById("notify_enabled").checked;' +
  '  var notifyTime = document.getElementById("notify_time").value || "08:00";' +
  '  if (!birthDate || !birthTime || isNaN(utcOffset) || isNaN(lat) || isNaN(lon)) {' +
  '    errorEl.textContent = "Please fill in all birth details.";' +
  '    errorEl.style.display = "block";' +
  '    return;' +
  '  }' +
  '  if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {' +
  '    errorEl.textContent = "Latitude must be -90..90, longitude -180..180.";' +
  '    errorEl.style.display = "block";' +
  '    return;' +
  '  }' +
  '  var dateParts = birthDate.split("-");' +
  '  var timeParts = birthTime.split(":");' +
  '  var notifyParts = notifyTime.split(":");' +
  '  var result = {' +
  '    birth_year: parseInt(dateParts[0], 10),' +
  '    birth_month: parseInt(dateParts[1], 10),' +
  '    birth_day: parseInt(dateParts[2], 10),' +
  '    birth_hour: parseInt(timeParts[0], 10),' +
  '    birth_minute: parseInt(timeParts[1], 10),' +
  '    birth_utc_offset_minutes: Math.round(utcOffset * 60),' +
  '    birth_lat_microdeg: Math.round(lat * 1000000),' +
  '    birth_lon_microdeg: Math.round(lon * 1000000),' +
  '    gender: gender,' +
  '    lang: lang,' +
  '    notify_enabled: notifyEnabled ? 1 : 0,' +
  '    notify_hour: parseInt(notifyParts[0], 10),' +
  '    notify_minute: parseInt(notifyParts[1], 10),' +
  '    saved_birth_date: birthDate,' +
  '    saved_birth_time: birthTime,' +
  '    saved_birth_utc_offset: utcOffset,' +
  '    saved_birth_lat: lat,' +
  '    saved_birth_lon: lon,' +
  '    saved_notify_time: notifyTime' +
  '  };' +
  '  document.location = "pebblejs://close#" + encodeURIComponent(JSON.stringify(result));' +
  '});';

function buildConfigHtml(saved) {
  var lang = saved.lang || 'en';
  var gender = typeof saved.gender === 'number' ? saved.gender : 0;
  var notifyChecked = saved.notify_enabled ? ' checked' : '';
  return '<!doctype html>' +
    '<html><head><meta charset="utf-8">' +
    '<meta name="viewport" content="width=device-width, initial-scale=1">' +
    '<title>Deck in a Dash Settings</title>' +
    '<style>' +
    'body{font-family:sans-serif;margin:0;padding:16px;background:#fff;color:#222;}' +
    'h1{font-size:20px;}' +
    'h2{font-size:15px;margin-top:24px;border-bottom:1px solid #ccc;padding-bottom:4px;}' +
    'label{display:block;margin-top:12px;font-size:13px;color:#555;}' +
    'input,select{width:100%;box-sizing:border-box;padding:8px;font-size:16px;margin-top:4px;' +
    'border:1px solid #ccc;border-radius:4px;}' +
    '.row{display:flex;gap:8px;}' +
    '.row>div{flex:1;}' +
    '.checkbox-row{display:flex;align-items:center;margin-top:16px;}' +
    '.checkbox-row input{width:auto;margin-right:8px;}' +
    'button{width:100%;margin-top:24px;padding:12px;font-size:16px;background:#5a3fc0;' +
    'color:#fff;border:none;border-radius:4px;}' +
    '.error{color:#c00;font-size:13px;margin-top:8px;display:none;}' +
    '</style></head><body>' +
    '<div style="text-align:center;">' +
    '<img src="' + LOGO_DATA_URI + '" width="120" height="120" alt="Deck in a Dash">' +
    '<h1 style="margin:8px 0 0;">Deck in a Dash</h1>' +
    '</div>' +
    '<form id="cfg">' +
    '<h2>Birth Details</h2>' +
    '<label>Birth date</label>' +
    '<input type="date" id="birth_date" value="' + escapeHtml(saved.birth_date) + '" required>' +
    '<label>Birth time (24h, local to birth place)</label>' +
    '<input type="time" id="birth_time" value="' + escapeHtml(saved.birth_time) + '" required>' +
    '<label>UTC offset at birth (hours, e.g. 2 for CEST)</label>' +
    '<input type="number" id="birth_utc_offset" step="0.25" min="-14" max="14" value="' +
    escapeHtml(saved.birth_utc_offset) + '" required>' +
    '<div class="row">' +
    '<div><label>Latitude (&deg;, north +)</label>' +
    '<input type="number" id="birth_lat" step="0.0001" min="-90" max="90" value="' +
    escapeHtml(saved.birth_lat) + '" required></div>' +
    '<div><label>Longitude (&deg;, east +)</label>' +
    '<input type="number" id="birth_lon" step="0.0001" min="-180" max="180" value="' +
    escapeHtml(saved.birth_lon) + '" required></div>' +
    '</div>' +
    '<label>Gender (used for reading pronouns)</label>' +
    '<select id="gender">' + buildGenderOptions(gender) + '</select>' +
    '<h2>Display</h2>' +
    '<label>Language</label>' +
    '<select id="lang">' + buildLanguageOptions(lang) + '</select>' +
    '<h2>Daily Notification</h2>' +
    '<div class="checkbox-row">' +
    '<input type="checkbox" id="notify_enabled"' + notifyChecked + '>' +
    '<label style="margin:0;">Notify me daily</label>' +
    '</div>' +
    '<label>Notification time</label>' +
    '<input type="time" id="notify_time" value="' + escapeHtml(saved.notify_time || '08:00') + '">' +
    '<div class="error" id="error"></div>' +
    '<button type="submit">Save</button>' +
    '</form>' +
    '<script>' + FORM_SCRIPT + '</script>' +
    '</body></html>';
}

Pebble.addEventListener('ready', function () {
  console.log('Deck in a Dash: pkjs ready, showConfiguration listener registered');
});

Pebble.addEventListener('showConfiguration', function () {
  console.log('Deck in a Dash: showConfiguration fired');
  var html = buildConfigHtml(loadSavedConfig());
  Pebble.openURL('data:text/html;charset=utf-8,' + encodeURIComponent(html));
});

Pebble.addEventListener('webviewclosed', function (e) {
  if (!e || !e.response) return;

  var result;
  try {
    result = JSON.parse(decodeURIComponent(e.response));
  } catch (err) {
    return; // Cancelled (no response) or a malformed payload - ignore.
  }

  saveConfig({
    birth_date: result.saved_birth_date,
    birth_time: result.saved_birth_time,
    birth_utc_offset: result.saved_birth_utc_offset,
    birth_lat: result.saved_birth_lat,
    birth_lon: result.saved_birth_lon,
    gender: result.gender,
    lang: result.lang,
    notify_enabled: result.notify_enabled === 1,
    notify_time: result.saved_notify_time
  });

  Pebble.sendAppMessage({
    BIRTH_YEAR: result.birth_year,
    BIRTH_MONTH: result.birth_month,
    BIRTH_DAY: result.birth_day,
    BIRTH_HOUR: result.birth_hour,
    BIRTH_MINUTE: result.birth_minute,
    BIRTH_UTC_OFFSET_MINUTES: result.birth_utc_offset_minutes,
    BIRTH_LAT_MICRODEG: result.birth_lat_microdeg,
    BIRTH_LON_MICRODEG: result.birth_lon_microdeg,
    GENDER: result.gender,
    LANG: result.lang,
    NOTIFY_ENABLED: result.notify_enabled,
    NOTIFY_HOUR: result.notify_hour,
    NOTIFY_MINUTE: result.notify_minute
  }, function () {
    console.log('Deck in a Dash: config sent to watch');
  }, function (err) {
    console.log('Deck in a Dash: config send failed: ' + JSON.stringify(err));
  });
});
