<template>
  <section class="settings-section" id="settings-section_elem" data-color-type="elem">
    <h2>Réglage du texte</h2>
    <div class="container"> 
  
    <p class="infos">
      Ces réglages s'appliquent à l'ensemble des éléments du document. Vous
      pouvez modifier ensuite les éléments indépendamment.
    </p>

    <!-- Police -->
    <div class="settings-subsection">
      <div class="field field-font">
        <label for="text-font" class="label-with-tooltip field--view-only" data-css="font-family" title="Fonctionnalité à venir">Police</label>
        <div class="field-with-option">
          <select id="text-font" v-model="font" disabled class="field--view-only" title="Fonctionnalité à venir">
            <option v-for="f in fonts" :key="f" :value="f">{{ f }}</option>
          </select>
          <div class="field-checkbox">
            <input id="text-italic" type="checkbox" v-model="italic" />
            <label for="text-italic" class="label-with-tooltip" data-css="font-style">Italique</label>
          </div>
        </div>
      </div>
    </div>

    <!-- Graisse -->
    <div class="settings-subsection">
      <div class="field">
        <label class="label-with-tooltip" data-css="font-weight">Graisse</label>
        <UnitToggle v-model="weight" :units="weights" />
      </div>
    </div>

    <!-- Taille du texte -->
    <div class="settings-subsection">
      <div class="field field-text-size">
        <label for="text-size-range" class="label-with-tooltip" data-css="font-size">Taille du texte</label>
        <InputWithUnit
          v-model="fontSize"
          :units="['px']"
          :min="8"
          :max="72"
          showRange
        />
      </div>
    </div>

    <!-- Alignement -->
    <div class="settings-subsection">
      <div class="field field-simple">
        <label for="text-alignment" class="label-with-tooltip" data-css="text-align">Alignement</label>
        <select id="text-alignment" v-model="alignment">
          <option v-for="a in alignments" :key="a.value" :value="a.value">
            {{ a.label }}
          </option>
        </select>
      </div>
    </div>

    <!-- Couleurs -->
    <div class="settings-subsection">
      <div class="field field-simple">
        <label for="text-color" class="label-with-tooltip" data-css="color">Couleur</label>
        <div class="input-with-color">
          <input
            ref="colorInput"
            id="text-color"
            type="text"
            v-model="color"
            class="color-input"
            data-coloris
          />
        </div>
      </div>
    </div>

      <!-- Couleurs // arrière plan -->
    <div class="settings-subsection">
      <div class="field field-simple">
        <label for="text-background" class="label-with-tooltip" data-css="background">Arrière-plan</label>
        <div class="input-with-color">
          <input
            ref="backgroundInput"
            id="text-background"
            type="text"
            v-model="background"
            class="color-input"
            data-coloris
          />
        </div>
      </div>
    </div>

    <!-- Marges extérieures -->
    <div class="settings-subsection margins">
      <div class="subsection-header">
        <h3>Marges extérieures</h3>
        <button
          type="button"
          class="link-button"
          :class="{ active: marginOuterLinked }"
          @click="marginOuterLinked = !marginOuterLinked"
          :title="marginOuterLinked ? 'Dissocier les marges' : 'Lier les marges'"
        >
          <svg v-if="marginOuterLinked" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M18.3638 15.5355L16.9496 14.1213L18.3638 12.7071C20.3164 10.7545 20.3164 7.58866 18.3638 5.63604C16.4112 3.68341 13.2453 3.68341 11.2927 5.63604L9.87849 7.05025L8.46428 5.63604L9.87849 4.22182C12.6122 1.48815 17.0443 1.48815 19.778 4.22182C22.5117 6.95549 22.5117 11.3876 19.778 14.1213L18.3638 15.5355ZM15.5353 18.364L14.1211 19.7782C11.3875 22.5118 6.95531 22.5118 4.22164 19.7782C1.48797 17.0445 1.48797 12.6123 4.22164 9.87868L5.63585 8.46446L7.05007 9.87868L5.63585 11.2929C3.68323 13.2455 3.68323 16.4113 5.63585 18.364C7.58847 20.3166 10.7543 20.3166 12.7069 18.364L14.1211 16.9497L15.5353 18.364ZM14.8282 7.75736L16.2425 9.17157L9.17139 16.2426L7.75717 14.8284L14.8282 7.75736Z"></path></svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M17 17H22V19H19V22H17V17ZM7 7H2V5H5V2H7V7ZM18.364 15.5355L16.9497 14.1213L18.364 12.7071C20.3166 10.7545 20.3166 7.58866 18.364 5.63604C16.4113 3.68342 13.2455 3.68342 11.2929 5.63604L9.87868 7.05025L8.46447 5.63604L9.87868 4.22183C12.6123 1.48816 17.0445 1.48816 19.7782 4.22183C22.5118 6.9555 22.5118 11.3877 19.7782 14.1213L18.364 15.5355ZM15.5355 18.364L14.1213 19.7782C11.3877 22.5118 6.9555 22.5118 4.22183 19.7782C1.48816 17.0445 1.48816 12.6123 4.22183 9.87868L5.63604 8.46447L7.05025 9.87868L5.63604 11.2929C3.68342 13.2455 3.68342 16.4113 5.63604 18.364C7.58866 20.3166 10.7545 20.3166 12.7071 18.364L14.1213 16.9497L15.5355 18.364ZM14.8284 7.75736L16.2426 9.17157L9.17157 16.2426L7.75736 14.8284L14.8284 7.75736Z"></path></svg>
        </button>
      </div>

      <div class="field field-margin">
        <label for="margin-outer-top" class="label-with-tooltip" data-css="margin-top">Haut</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-outer-top"
            :modelValue="marginOuterDetailed.top.value"
            @update:modelValue="(value) => marginOuterDetailed.top.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginOuterDetailed.top.unit === 'mm' }"
              @click="updateMarginOuterUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginOuterDetailed.top.unit === 'px' }"
              @click="updateMarginOuterUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginOuterDetailed.top.unit === 'rem' }"
              @click="updateMarginOuterUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-outer-bottom" class="label-with-tooltip" data-css="margin-bottom">Bas</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-outer-bottom"
            :modelValue="marginOuterDetailed.bottom.value"
            @update:modelValue="(value) => marginOuterDetailed.bottom.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginOuterDetailed.bottom.unit === 'mm' }"
              @click="updateMarginOuterUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginOuterDetailed.bottom.unit === 'px' }"
              @click="updateMarginOuterUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginOuterDetailed.bottom.unit === 'rem' }"
              @click="updateMarginOuterUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-outer-left" class="label-with-tooltip" data-css="margin-left">Gauche</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-outer-left"
            :modelValue="marginOuterDetailed.left.value"
            @update:modelValue="(value) => marginOuterDetailed.left.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginOuterDetailed.left.unit === 'mm' }"
              @click="updateMarginOuterUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginOuterDetailed.left.unit === 'px' }"
              @click="updateMarginOuterUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginOuterDetailed.left.unit === 'rem' }"
              @click="updateMarginOuterUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-outer-right" class="label-with-tooltip" data-css="margin-right">Droite</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-outer-right"
            :modelValue="marginOuterDetailed.right.value"
            @update:modelValue="(value) => marginOuterDetailed.right.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginOuterDetailed.right.unit === 'mm' }"
              @click="updateMarginOuterUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginOuterDetailed.right.unit === 'px' }"
              @click="updateMarginOuterUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginOuterDetailed.right.unit === 'rem' }"
              @click="updateMarginOuterUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>
    </div>

    <!-- Marges intérieures -->
    <div class="settings-subsection margins">
      <div class="subsection-header">
        <h3>Marges intérieures</h3>
        <button
          type="button"
          class="link-button"
          :class="{ active: marginInnerLinked }"
          @click="marginInnerLinked = !marginInnerLinked"
          :title="marginInnerLinked ? 'Dissocier les marges' : 'Lier les marges'"
        >
          <svg v-if="marginInnerLinked" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M18.3638 15.5355L16.9496 14.1213L18.3638 12.7071C20.3164 10.7545 20.3164 7.58866 18.3638 5.63604C16.4112 3.68341 13.2453 3.68341 11.2927 5.63604L9.87849 7.05025L8.46428 5.63604L9.87849 4.22182C12.6122 1.48815 17.0443 1.48815 19.778 4.22182C22.5117 6.95549 22.5117 11.3876 19.778 14.1213L18.3638 15.5355ZM15.5353 18.364L14.1211 19.7782C11.3875 22.5118 6.95531 22.5118 4.22164 19.7782C1.48797 17.0445 1.48797 12.6123 4.22164 9.87868L5.63585 8.46446L7.05007 9.87868L5.63585 11.2929C3.68323 13.2455 3.68323 16.4113 5.63585 18.364C7.58847 20.3166 10.7543 20.3166 12.7069 18.364L14.1211 16.9497L15.5353 18.364ZM14.8282 7.75736L16.2425 9.17157L9.17139 16.2426L7.75717 14.8284L14.8282 7.75736Z"></path></svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M17 17H22V19H19V22H17V17ZM7 7H2V5H5V2H7V7ZM18.364 15.5355L16.9497 14.1213L18.364 12.7071C20.3166 10.7545 20.3166 7.58866 18.364 5.63604C16.4113 3.68342 13.2455 3.68342 11.2929 5.63604L9.87868 7.05025L8.46447 5.63604L9.87868 4.22183C12.6123 1.48816 17.0445 1.48816 19.7782 4.22183C22.5118 6.9555 22.5118 11.3877 19.7782 14.1213L18.364 15.5355ZM15.5355 18.364L14.1213 19.7782C11.3877 22.5118 6.9555 22.5118 4.22183 19.7782C1.48816 17.0445 1.48816 12.6123 4.22183 9.87868L5.63604 8.46447L7.05025 9.87868L5.63604 11.2929C3.68342 13.2455 3.68342 16.4113 5.63604 18.364C7.58866 20.3166 10.7545 20.3166 12.7071 18.364L14.1213 16.9497L15.5355 18.364ZM14.8284 7.75736L16.2426 9.17157L9.17157 16.2426L7.75736 14.8284L14.8284 7.75736Z"></path></svg>
        </button>
      </div>

      <div class="field field-margin">
        <label for="margin-inner-top" class="label-with-tooltip" data-css="padding-top">Haut</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-inner-top"
            :modelValue="marginInnerDetailed.top.value"
            @update:modelValue="(value) => marginInnerDetailed.top.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginInnerDetailed.top.unit === 'mm' }"
              @click="updateMarginInnerUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginInnerDetailed.top.unit === 'px' }"
              @click="updateMarginInnerUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginInnerDetailed.top.unit === 'rem' }"
              @click="updateMarginInnerUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-inner-bottom" class="label-with-tooltip" data-css="padding-bottom">Bas</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-inner-bottom"
            :modelValue="marginInnerDetailed.bottom.value"
            @update:modelValue="(value) => marginInnerDetailed.bottom.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginInnerDetailed.bottom.unit === 'mm' }"
              @click="updateMarginInnerUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginInnerDetailed.bottom.unit === 'px' }"
              @click="updateMarginInnerUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginInnerDetailed.bottom.unit === 'rem' }"
              @click="updateMarginInnerUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-inner-left" class="label-with-tooltip" data-css="padding-left">Gauche</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-inner-left"
            :modelValue="marginInnerDetailed.left.value"
            @update:modelValue="(value) => marginInnerDetailed.left.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginInnerDetailed.left.unit === 'mm' }"
              @click="updateMarginInnerUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginInnerDetailed.left.unit === 'px' }"
              @click="updateMarginInnerUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginInnerDetailed.left.unit === 'rem' }"
              @click="updateMarginInnerUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>

      <div class="field field-margin">
        <label for="margin-inner-right" class="label-with-tooltip" data-css="padding-right">Droite</label>
        <div class="input-with-unit">
          <NumberInput
            id="margin-inner-right"
            :modelValue="marginInnerDetailed.right.value"
            @update:modelValue="(value) => marginInnerDetailed.right.value = value"
            :min="0"
            :step="1"
          />
          <div class="unit-toggle">
            <button
              type="button"
              :class="{ active: marginInnerDetailed.right.unit === 'mm' }"
              @click="updateMarginInnerUnit('mm')"
            >mm</button>
            <button
              type="button"
              :class="{ active: marginInnerDetailed.right.unit === 'px' }"
              @click="updateMarginInnerUnit('px')"
            >px</button>
            <!-- <button
              type="button"
              :class="{ active: marginInnerDetailed.right.unit === 'rem' }"
              @click="updateMarginInnerUnit('rem')"
            >rem</button> -->
          </div>
        </div>
      </div>
    </div>

  </div>
  </section>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { initColoris } from '../../composables/useColoris';
import UnitToggle from '../ui/UnitToggle.vue';
import InputWithUnit from '../ui/InputWithUnit.vue';
import NumberInput from '../ui/NumberInput.vue';
import { useCssUpdater } from '../../composables/useCssUpdater';
import { useCssSync } from '../../composables/useCssSync';
import { useDebounce } from '../../composables/useDebounce';
import { useLinkedSpacing } from '../../composables/useLinkedSpacing';

const { updateStyle, setMargin, setDetailedMargins, setPadding, setDetailedPadding } = useCssUpdater();
const { extractValue, extractNumericValue, extractSpacing } = useCssSync();
const { debouncedUpdate } = useDebounce(500);

// Constants
const fonts = ['Alegreya Sans', 'Arial', 'Georgia', 'Helvetica', 'Times New Roman'];
const weights = ['200', '300', '400', '600', '800', 'normal', 'bold'];
const alignments = [
  { value: 'left', label: 'Gauche' },
  { value: 'center', label: 'Centre' },
  { value: 'right', label: 'Droite' },
  { value: 'justify', label: 'Justifié' }
];

// State
const font = ref('Alegreya Sans');
const italic = ref(false);
const weight = ref('400');
const fontSize = ref({ value: 16, unit: 'px' });
const alignment = ref('left');
const color = ref('rgb(0, 0, 0)');
const background = ref('transparent');
const colorInput = ref(null);
const backgroundInput = ref(null);

let isUpdatingFromStore = false;

const {
  sides: marginOuterDetailed,
  linked: marginOuterLinked,
  updateUnit: updateMarginOuterUnit,
  setFromSpacing: setMarginOuterFromSpacing,
} = useLinkedSpacing({
  initialValues: {
    top: { value: 0, unit: 'mm' },
    right: { value: 0, unit: 'mm' },
    bottom: { value: 24, unit: 'mm' },
    left: { value: 0, unit: 'mm' },
  },
  isUpdatingFromStore: () => isUpdatingFromStore,
  debouncedUpdate,
  onUpdate: (s) => {
    setDetailedMargins('p', s.top, s.right, s.bottom, s.left);
  },
});

const {
  sides: marginInnerDetailed,
  linked: marginInnerLinked,
  updateUnit: updateMarginInnerUnit,
  setFromSpacing: setMarginInnerFromSpacing,
} = useLinkedSpacing({
  isUpdatingFromStore: () => isUpdatingFromStore,
  debouncedUpdate,
  onUpdate: (s) => {
    setDetailedPadding('p', s.top, s.right, s.bottom, s.left);
  },
});

// Watchers for body styles
watch(font, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('body', 'font-family', `"${val}"`);
});

watch(italic, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('p', 'font-style', val ? 'italic' : 'normal');
});

watch(alignment, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('body', 'text-align', val);
});

watch(color, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('body', 'color', val);
});

watch(background, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('p', 'background', val);
});

// Watchers for paragraph styles
watch(weight, (val) => {
  if (isUpdatingFromStore) return;
  updateStyle('p', 'font-weight', val);
});

watch(fontSize, (val) => {
  if (isUpdatingFromStore) return;
  debouncedUpdate(() => {
    updateStyle('p', 'font-size', `${val.value}${val.unit}`);
  });
}, { deep: true });


// Sync from store
const syncFromStore = () => {
  isUpdatingFromStore = true;

  // Body styles
  const fontStyle = extractValue('p', 'font-style');
  if (fontStyle) italic.value = fontStyle === 'italic';

  const textAlign = extractValue('body', 'text-align');
  if (textAlign) alignment.value = textAlign;

  const colorVal = extractValue('body', 'color');
  if (colorVal) color.value = colorVal;

  const bgVal = extractValue('p', 'background');
  if (bgVal) background.value = bgVal;

  // Paragraph styles
  const fontWeight = extractValue('p', 'font-weight');
  if (fontWeight) weight.value = fontWeight;

  const fontSizeVal = extractNumericValue('p', 'font-size', ['px']); // ['px', 'em', 'rem']
  if (fontSizeVal) fontSize.value = fontSizeVal;

  // Margins
  const margins = extractSpacing('p', 'margin');
  if (margins) setMarginOuterFromSpacing(margins);

  // Padding
  const padding = extractSpacing('p', 'padding');
  if (padding) setMarginInnerFromSpacing(padding);

  isUpdatingFromStore = false;
};

const updateColorisButtons = () => {
  [colorInput.value, backgroundInput.value].forEach((input) => {
    if (input) {
      input.dispatchEvent(new Event('input', { bubbles: true }));
    }
  });
};

onMounted(() => {
  initColoris({
    format: 'auto',
    swatches: ['#000000', '#FFFFFF', '#FF0000', '#00FF00', '#0000FF', 'transparent'],
  });
  syncFromStore();
  setTimeout(updateColorisButtons, 100);
});
</script>

<style scoped>
.subsection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.subsection-header h3 {
  margin: 0;
}

.link-button {
  background: none;
  border: 1px solid var(--color-border, #ddd);
  border-radius: 4px;
  padding: 0.25rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  width: 24px;
  height: 24px;
}

.link-button svg {
  width: 16px;
  height: 16px;
  color: var(--color-text-secondary, #666);
}

.link-button:hover {
  background: var(--color-hover, #f0f0f0);
}

.link-button.active {
  background: var(--color-primary, #007bff);
  border-color: var(--color-primary, #007bff);
}

.link-button.active svg {
  color: white;
}
</style>
