package eu.friedcutlet.yokan.ui.screens.reader import eu.friedcutlet.yokan.database.DbReaderMode enum class ReaderDirection { Ltr, Rtl } data class ReaderPageShape(val width: Int, val height: Int) { val valid: Boolean get() = width > 0 && height > 0 val wide: Boolean get() = valid && width.toDouble() / height >= 1.35 val tall: Boolean get() = valid && height.toDouble() / width >= 2.5 } data class ReaderViewport(val widthDp: Int = 0, val heightDp: Int = 0) data class ResolvedReaderLayout(val mode: DbReaderMode, val direction: ReaderDirection, val pairPages: Boolean) internal const val AUTOMATIC_LAYOUT_VERSION = 1 internal const val AUTOMATIC_LAYOUT_SAMPLE_COUNT = 3 internal const val AUTOMATIC_LAYOUT_SAMPLE_TIMEOUT = 1500L /** At least two valid pages for multi-page chapters; mixed samples keep the user's fallback. */ fun automaticWebtoonSample(sample: List, chapterPageCount: Int): Boolean { val valid = sample.filter { it.valid }.take(AUTOMATIC_LAYOUT_SAMPLE_COUNT) val minimum = if (chapterPageCount == 1) 1 else 2 return valid.size >= minimum && valid.count { it.tall }.toDouble() / valid.size >= 0.75 } /** Direction comes only from explicit metadata or the fallback, never image aspect or language. */ fun resolveAutomaticReaderLayout( fallback: DbReaderMode, webtoon: Boolean, viewport: ReaderViewport, explicitDirection: ReaderDirection? = null, pairingOverride: Boolean? = null, settled: Boolean = true, ): ResolvedReaderLayout { val direction = explicitDirection ?: if (fallback.isRightToLeft()) ReaderDirection.Rtl else ReaderDirection.Ltr val mode = if (webtoon) DbReaderMode.Webtoon else when { explicitDirection != null && fallback.isHorizontalContinuous() -> if (direction == ReaderDirection.Rtl) DbReaderMode.HorizontalContinuousRtl else DbReaderMode.HorizontalContinuous explicitDirection != null && (fallback == DbReaderMode.Rtl || fallback == DbReaderMode.Ltr) -> if (direction == ReaderDirection.Rtl) DbReaderMode.Rtl else DbReaderMode.Ltr else -> fallback } val pair = pairingOverride ?: (settled && mode.isPaged() && viewport.widthDp >= 840 && viewport.widthDp > viewport.heightDp) return ResolvedReaderLayout(mode, direction, pair) } internal fun automaticLayoutHasWebtoonMetadata(genres: List): Boolean = genres.any { it.trim().lowercase() in setOf("webtoon", "long strip", "long-strip") }