/* Reusable media/file uploader with camera capture + gallery + lightbox.
   Mobile advantage: <input capture="environment"> opens the rear camera.
   Mock mode keeps files client-side (objectURL); wiring to Upload*File endpoints
   is a drop-in swap in addFiles(). */
(function () {
    function fmtSize(b) {
        if (b == null) return '';
        if (b < 1024) return b + ' B';
        if (b < 1048576) return (b / 1024).toFixed(0) + ' KB';
        return (b / 1048576).toFixed(1) + ' MB';
    }
    function seedPhoto(label, hue) {
        var c = document.createElement('canvas'); c.width = 300; c.height = 220;
        var x = c.getContext('2d');
        var g = x.createLinearGradient(0, 0, 300, 220);
        g.addColorStop(0, 'hsl(' + hue + ',45%,55%)'); g.addColorStop(1, 'hsl(' + (hue + 40) + ',40%,35%)');
        x.fillStyle = g; x.fillRect(0, 0, 300, 220);
        x.fillStyle = 'rgba(255,255,255,.9)'; x.font = 'bold 20px system-ui'; x.fillText(label, 16, 200);
        x.strokeStyle = 'rgba(255,255,255,.5)'; x.lineWidth = 2; x.strokeRect(20, 20, 120, 80);
        return c.toDataURL('image/jpeg', 0.7);
    }

    Vue.component('media-uploader', {
        props: { title: { type: String, default: 'Fayllar və fotolar' }, seed: { type: Boolean, default: true } },
        data: function () {
            var files = [];
            if (this.seed) {
                files = [
                    { id: 1, name: 'Fasad.jpg', type: 'image/jpeg', url: seedPhoto('Fasad', 190), size: 184320, date: Date.now() - 86400000 },
                    { id: 2, name: 'Karkas.jpg', type: 'image/jpeg', url: seedPhoto('Karkas', 30), size: 210000, date: Date.now() - 3600000 },
                    { id: 3, name: 'Layihə_reyi.pdf', type: 'application/pdf', url: '', size: 542000, date: Date.now() - 2 * 86400000 }
                ];
            }
            return { files: files, lightbox: -1, seq: 100 };
        },
        computed: {
            images: function () { return this.files.filter(function (f) { return /^image\//.test(f.type); }); }
        },
        methods: {
            fmtSize: fmtSize,
            fmtDate: function (t) { return window.fmt.date(new Date(t)); },
            isImage: function (f) { return /^image\//.test(f.type); },
            fileIcon: function (f) {
                if (/pdf/.test(f.type)) return 'fa-file-pdf';
                if (/word|doc/.test(f.type)) return 'fa-file-word';
                if (/sheet|excel|xls/.test(f.type)) return 'fa-file-excel';
                return 'fa-file';
            },
            pick: function (which) { this.$refs[which].click(); },
            onPick: function (e) {
                var self = this, list = e.target.files || [];
                Array.prototype.forEach.call(list, function (file) {
                    self.files.unshift({
                        id: ++self.seq, name: file.name, type: file.type || 'application/octet-stream',
                        url: /^image\//.test(file.type) ? URL.createObjectURL(file) : '', size: file.size, date: Date.now(), _local: true
                    });
                });
                if (list.length) toastr.success(list.length + ' fayl əlavə edildi');
                e.target.value = '';
                // real: await API.post('/Objects/UploadObjectFile', formData)
            },
            remove: function (f) {
                if (f._local && f.url) URL.revokeObjectURL(f.url);
                this.files = this.files.filter(function (x) { return x.id !== f.id; });
            },
            open: function (f) {
                if (this.isImage(f)) this.lightbox = this.images.findIndex(function (x) { return x.id === f.id; });
                else toastr.info('Yüklənir: ' + f.name);   // real: download endpoint
            },
            lbNav: function (d) {
                var n = this.images.length; if (!n) { this.lightbox = -1; return; }
                this.lightbox = (this.lightbox + d + n) % n;
            }
        },
        template: `
        <div>
            <input ref="camera" type="file" accept="image/*" capture="environment" class="u-hide" @change="onPick">
            <input ref="gallery" type="file" accept="image/*,application/pdf,.doc,.docx,.xls,.xlsx" multiple class="u-hide" @change="onPick">

            <div class="section-head mt0"><h3>{{ title }}</h3><span class="count">{{ files.length }} fayl</span></div>

            <div class="u-row u-mb g-8">
                <button class="btn btn--brand u-grow" @click="pick('camera')"><i class="fa-light fa-camera"></i>Kamera</button>
                <button class="btn btn--outline u-grow" @click="pick('gallery')"><i class="fa-light fa-folder-open"></i>Fayl seç</button>
            </div>

            <ui-empty v-if="!files.length" icon="fa-light fa-images" title="Fayl yoxdur" hint="Kamera və ya qalereyadan əlavə edin"></ui-empty>

            <div v-else class="media-grid">
                <div v-for="f in files" :key="f.id" class="media-tile" @click="open(f)">
                    <img v-if="isImage(f)" :src="f.url" :alt="f.name" loading="lazy">
                    <div v-else class="media-tile__file"><i class="fa-light" :class="fileIcon(f)"></i></div>
                    <button class="media-tile__del" @click.stop="remove(f)"><i class="fa-light fa-xmark"></i></button>
                    <div class="media-tile__cap"><span>{{ f.name }}</span><small>{{ fmtSize(f.size) }}</small></div>
                </div>
            </div>

            <!-- Lightbox -->
            <div v-if="lightbox>=0 && images[lightbox]" class="lightbox" @click.self="lightbox=-1">
                <button class="lightbox__close" @click="lightbox=-1"><i class="fa-light fa-xmark"></i></button>
                <button v-if="images.length>1" class="lightbox__nav lightbox__nav--prev" @click.stop="lbNav(-1)"><i class="fa-light fa-chevron-left"></i></button>
                <img :src="images[lightbox].url" :alt="images[lightbox].name">
                <button v-if="images.length>1" class="lightbox__nav lightbox__nav--next" @click.stop="lbNav(1)"><i class="fa-light fa-chevron-right"></i></button>
                <div class="lightbox__cap">{{ images[lightbox].name }} · {{ lightbox+1 }}/{{ images.length }}</div>
            </div>
        </div>`
    });
})();
